c++ 判断成员变量和函数是否存在

  • Post author:
  • Post category:其他


这个自己查的资料,好多都是直接讲理论,说到代码就唧唧了。自己尝试写了一哈,在vs2015下测试通过。


example_1.cpp

#include <iostream>
#include <type_traits>

using namespace std;

/*
解决了检查成员函数是否存在的问题,
参考链接
https://www.csdn.net/article/2015-12-03/2826381

*/


#define HAS_MEMBER(member)\
template<typename T, typename... Args>struct has_member_##member\
{\
	private:\
		template<typename U> static auto Check(int) -> decltype(std::declval<U>().member(std::declval<Args>()...), std::true_type());\
		template<typename U> static std::false_type Check(...);\
	public:\
		enum{value = std::is_same<decltype(Check<T>(0)), std::true_type>::value};\
};

HAS_MEMBER(foo)
HAS_MEMBER(func)

struct MyStruct
{
	string foo() { return ""; }
	int func(int i) { return i; }
};





int example_1(int argc, char * argv[])
{
	cout << "cl_int2=" << has_member_foo<MyStruct>::value << endl;
	cout << "cl_int2=" << has_member_func<MyStruct, int>::value << endl;
	

	//cout << "cl_int2=" << typeid(has_member<float>::type).name() << endl;
	//cout << "int=" << has_member<float>::value << endl;//对比测试

	system("pause");
	return 0;
}
#include <iostream>
#include <type_traits>

using namespace std;

/*
解决了检查成员函数是否存在的问题,
参考链接
https://www.csdn.net/article/2015-12-03/2826381

*/




/* 模板函数,检查T是否有名为's'的成员
* value 为bool型检查结果
* type为s成员的类型(value为true是有效)
*/
#define HAS_MEMBER_S(member)\
template<typename T>struct has_member_##member\
{\
	template <typename _T>static auto check(_T)->typename std::decay<decltype(_T::member)>::type;\
	static void check(...);\
	using type = decltype(check(std::declval<T>()));\
	enum { value = !std::is_void<type>::value };\
};	



HAS_MEMBER_S(s)

struct  e
{
	char s[2];
	int   v2;

};
int main(int argc, char * argv[])
{
	cout << "cl_int2=" << has_member_s<e>::value << endl;
	
	//cout << "cl_int2=" << typeid(has_member<float>::type).name() << endl;
	//cout << "int=" << has_member<float>::value << endl;//对比测试

	system("pause");
	return 0;
}



版权声明:本文为qq_28691955原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。