[英]Trait template class for checking if a class has a member with specific name
I made this code for checking if a class has a member called first:我制作了这段代码来检查 class 是否有一个叫 first 的成员:
template <class T>
struct ClassA{
T first;
};
template <class T>
struct ClassB{
T second;
};
template <class T>
struct has_member_named_first
{
typedef char valid_type;
typedef struct { char array[2]; } not_valid_type;
template <typename U>
static valid_type __test(typename U::first*);
template <typename U>
static not_valid_type __test(...);
static const bool value = sizeof(__test<T>(0)) == sizeof(valid_type);
};
By defining valid_type
as char and not_valid_type
as struct { char array[2];通过将valid_type
定义为 char 并将not_valid_type
定义为 struct { char array[2]; } we can make the last line sizeof(__test<T>(0)) == sizeof(valid_type);
} 我们可以让最后一行sizeof(__test<T>(0)) == sizeof(valid_type);
return true or false based on the instantiated function __test and thus determine if a class has a member named first
.根据实例化的 function __test 返回 true 或 false,从而确定 class 是否有名为first
的成员。
int main()
{
std::cout << has_type_named_first<ClassA<int> >::value << std::endl;
std::cout << has_type_named_first<ClassB<int> >::value << std::endl;
return (0);
}
but i got in the output:但我进入了 output:
0 0
0 0
In C++98, checks for if an expression is valid using SFINAE can be done like this:在 C++98 中,使用 SFINAE 检查表达式是否有效可以像这样完成:
template <class T>
struct has_member_named_first
{
private:
typedef char valid_type;
typedef char(¬_valid_type)[2];
template<std::size_t> struct check_expr;
template <typename U>
static valid_type test(check_expr<sizeof((void) (YOUR_EXPRESSION_HERE), 0)>*);
template <typename U>
static not_valid_type test(...);
public:
static const bool value = sizeof(test<T>(0)) == sizeof(valid_type);
};
To check for a data member, you can have YOUR_EXPRESSION_HERE
be static_cast<U*>(0)->first
or simply U::first
.要检查数据成员,您可以将YOUR_EXPRESSION_HERE
设置为static_cast<U*>(0)->first
或简单地设置为U::first
。
To check for a member function or data member, use &U::first
.要检查成员 function 或数据成员,请使用&U::first
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.