结构体是否包含特定类型的成员变量

时间:2024-11-11 09:07:37
#include <iostream> #include <type_traits> struct S1 { int id = 0; }; struct S2 { int id = 0; std::string code; }; // 检查T类型是否包含名为'code'的std::string类型成员变量 template <typename T, typename = void> struct has_code : std::false_type {}; template <typename T> struct has_code<T, std::void_t<decltype(T::code)>> : std::is_same<decltype(T::code), std::string> {}; // 辅助变量模板 #if _HAS_CXX17 template <typename T> inline constexpr bool has_code_v = has_code<T>::value; #else template <typename T> constexpr bool has_code_v = has_code<T>::value; #endif int main() { std::cout << std::boolalpha; std::cout << "S1 has code: " << has_code_v<S1> << std::endl; // 输出: false std::cout << "S2 has code: " << has_code_v<S2> << std::endl; // 输出: true return 0; }

相关文章