[c++11] 判断 类内是否有指定名字的 字段/成员函数/静态函数/typedef

之前的文章里……比较那啥,

总之这个版本可以分别 判断字段/成员函数/静态函数/typedef

主要用了c++11的decltype和一些萃取类,这次就没办法用变通的方式放到低版本去了

注意,对于成员函数或静态函数,如果有重载比如 a() a(int) 反而会得到0的结果

后面提供了一种验证语法可行性的方法,可以解决重载问题

#include "stdafx.h"
#include <xtr1common>
#include <string>


template<typename T, typename C = std::enable_if <std::is_member_object_pointer<decltype(&T::first)>::value >::type>
short existFirst()
{}
template<typename T>
char existFirst(...)
{}

template<typename T, typename C = std::enable_if <std::is_member_function_pointer<decltype(&T::c_str)>::value >::type>
short exist_c_str()
{}
template<typename T>
char exist_c_str(...)
{}

template<typename T, typename C = std::enable_if <std::is_function<std::remove_pointer_t<decltype(&T::staticfun)>>::value >::type>
short exist_staticfun()
{
	return 0;
}
template<typename T>
char exist_staticfun(...)
{}

template<typename T, typename C = std::enable_if <std::is_pointer<T::first_type*>::value >::type>
short exist_first_type()
{}
template<typename T>
char exist_first_type(...)
{}

template<typename T, typename C = std::enable_if <std::is_integral<decltype(((T*)0)->first(), 1)>::value>::type>
short exist_member_fun_overload()
{
}
template<typename T>
char exist_member_fun_overload(...)
{
}


struct A
{
	static void staticfun();
//	void first();
	void first();
};
struct B
{
	void staticfun();
	void first_type();
	static void c_str();
	void first(int);
};

int _tmain(int argc, _TCHAR* argv[])
{
	printf("%d\n", sizeof(existFirst<std::pair<int, int>>()) - 1);		//1
	printf("%d\n", sizeof(existFirst<std::string>()) - 1);				//0
	printf("%d\n", sizeof(existFirst<int>()) - 1);						//0
	printf("%d\n", sizeof(existFirst<A>()) - 1);						//0
	puts("");
	printf("%d\n", sizeof(exist_c_str<std::pair<int, int>>()) - 1);		//0
	printf("%d\n", sizeof(exist_c_str<std::string>()) - 1);				//1
	printf("%d\n", sizeof(exist_c_str<int>()) - 1);						//0
	printf("%d\n", sizeof(exist_c_str<B>()) - 1);						//0
	puts("");
	printf("%d\n", sizeof(exist_first_type<std::pair<int, int>>()) - 1);//1
	printf("%d\n", sizeof(exist_first_type<std::string>()) - 1);		//0
	printf("%d\n", sizeof(exist_first_type<int>()) - 1);				//0
	printf("%d\n", sizeof(exist_first_type<B>()) - 1);					//0
	puts("");
	printf("%d\n", sizeof(exist_staticfun<B>()) - 1);					//0
	printf("%d\n", sizeof(exist_staticfun<A>()) - 1);					//1
	printf("%d\n", sizeof(exist_staticfun<std::string>()) - 1);			//0
	printf("%d\n", sizeof(exist_staticfun<int>()) - 1);					//0

	puts("");
	printf("%d\n", sizeof(exist_member_fun_overload<A>()) - 1);					//1
	printf("%d\n", sizeof(exist_member_fun_overload<B>()) - 1);					//0
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值