模板函数对象当函数使用

分析下边的模板类,在什么情况下返回空指针

template <typename T>
struct get_visitor{
	typedef T* result_type;
	result_type operator()(T& val) const {return & val;
	}
	template <typename U>
	result_type operator()(const U& ) const {return nullptr;
	}
};

我们知道  类里边 operator ()  是函数对象

函数对象也可以当函数使用

比如 

struct Printer{
    void operator()(const std::string & str)const{
        std::cout<<str<<std::endl;
    }
};
int main() {
	Printer print;
	print("hello world");
	// or 
	Printer()("hello world");

	return 0;
}

那么同样的,对于开头说展示的这个模板

int main() {
	int a = 10;
    string b = "abc";
	cout<<&a<<endl;
	auto g_a= get_visitor<int>()(a) ;
	auto g_b= get_visitor<int>()(b) ;
	cout<< typeid(g_a).name()<<endl; 
	cout<< g_a<<endl;
	cout<< g_b<<endl;
	return 0;
}
// console ouput
/*
 0x7ffd5856a838
 Pi  //pointer to type int
 0x7ffd5856a838
 0   // nullptr
*/

那么这个 get_visitor 模板的作用就是,获取传入数据的地址,如果类型不匹配就返回 空指针

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值