最近程序出现了crash 问题,追踪代码的时候,发现了这个模板类,是因为其返回了 空指针导致的,然后就做了一些实验

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-06 18:09