Last active
August 16, 2023 16:05
-
-
Save jerrylususu/e1da95f10ad32413e7dfc1a9f3b8df91 to your computer and use it in GitHub Desktop.
cpp check member exist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// should read | |
// https://hedzr.com/c++/algorithm/cxx-is_detected-and-detection-idioms | |
#include <iostream> | |
#include <type_traits> | |
#include <experimental/type_traits> | |
// AClass definition | |
class AClass { | |
public: | |
std::string dueDate; | |
std::string title; | |
void setDueDate(const std::string& date) { | |
dueDate = date; | |
} | |
}; | |
// BClass definition | |
class BClass { | |
public: | |
std::string title; | |
}; | |
template<typename T> | |
using setDueDate_t = decltype( std::declval<T&>().setDueDate("") ); | |
template<typename T> | |
constexpr bool has_setDueDate = std::experimental::is_detected_v<setDueDate_t, T>; | |
// MetaDataSetter class | |
template <typename T> | |
class MetaDataSetter { | |
public: | |
static void setMetaData(T& obj) { | |
obj.title = "example"; | |
if constexpr (has_setDueDate<T>) { | |
std::cout << "in" << std::endl; | |
obj.setDueDate("example date ehere!"); | |
} else { | |
std::cout << "out" << std::endl; | |
} | |
} | |
}; | |
int main() { | |
AClass aObj; | |
BClass bObj; | |
MetaDataSetter<AClass>::setMetaData(aObj); | |
MetaDataSetter<BClass>::setMetaData(bObj); | |
std::cout << "AClass: " << aObj.title << ", " << aObj.dueDate << std::endl; | |
std::cout << "BClass: " << bObj.title << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment