模板函數對象當函數使用

分析下邊的模板類,在什麼情況下返回空指針

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 模板的作用就是,獲取傳入數據的地址,如果類型不匹配就返回 空指針

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章