Skip to content

Instantly share code, notes, and snippets.

@jerrylususu
Last active August 16, 2023 16:05
Show Gist options
  • Save jerrylususu/e1da95f10ad32413e7dfc1a9f3b8df91 to your computer and use it in GitHub Desktop.
Save jerrylususu/e1da95f10ad32413e7dfc1a9f3b8df91 to your computer and use it in GitHub Desktop.
cpp check member exist
// 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