C++模板判断类是否存在某个成员变量

#include 
#include 

// 检查 xxxx 是否是类T的成员
template 
struct has_member_xxxx
{
	// 如果 &T::xxxx 合法, 本函数就合法
	// 下面check(0)优先调用本函数, 返回值是void
	template
	static void check(decltype(&U::xxxx));

	// 否则, 下面chech(0)调用本函数
	// 返回值是int
	template
	static int check(...);

	// 如果check(0)的返回值是void, 
	// 则&T::xxxx合法, xxxx是T的成员
	enum { value = std::is_void(0))>::value };
};


struct A
{
	int xxxx;
};

struct B
{
	void xxxx() {};
};

struct C
{
};

int main(int argc, char** argv)
{
	std::cout << "A::xxxx = " << has_member_xxxx::value << std::endl;
	std::cout << "B::xxxx = " << has_member_xxxx::value << std::endl;
	std::cout << "C::xxxx = " << has_member_xxxx::value << std::endl;

	return 0;
}

/*
运行输出
A::xxxx = 1
B::xxxx = 1
C::xxxx = 0
*/

一种更简洁的实现, 见 https://blog.csdn.net/netyeaxi/article/details/83479646

你可能感兴趣的:(C++FAQ,算法)