Skip to content

Instantly share code, notes, and snippets.

@breeze1990
Last active December 23, 2022 05:46
Show Gist options
  • Save breeze1990/a9ba3e4e2371ff113cb1b1b5a1968d84 to your computer and use it in GitHub Desktop.
Save breeze1990/a9ba3e4e2371ff113cb1b1b5a1968d84 to your computer and use it in GitHub Desktop.
detect if a class has specific static field of specific type in C++
#include <iostream>
#include "type_checker.h"
typedef struct payload {} payload;
typedef struct payload2 {
static std::string id;
} payload2;
std::string payload2::id;
int main() {
std::cout << has_static_id<payload>::value << std::endl; // 0
std::cout << has_static_id<payload2>::value << std::endl; // 1
return 0;
}
#include <type_traits>
// reference https://stackoverflow.com/a/16000226
template<typename T, typename = void>
struct has_static_id : std::false_type {
};
template<typename T>
struct has_static_id<T, typename std::enable_if<std::is_same<std::string, std::decay_t<decltype(T::id)>>::value, void>::type> : std::true_type {
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment