问题描述
|
如果模板参数是一个指针(或智能指针),或者该参数不是它,该如何保留它的引用呢?
template<class T> void subf(const T& item)
{
item.foo();
}
template<class T> void f(const T& item)
{
subf(magic_dereference_function(item));
}
Boost中的任何内容都是可以选择的。
解决方法
template <typename T>
T& maybe_deref(T& x) { return x; }
template <typename T>
T& maybe_deref(T* x) { return *x; }
您必须为智能指针分别添加重载。无法检测类是否为“智能指针”。您可以检测到operator->
的存在,但这并不意味着它是一个聪明的指针。
, 过载如何?
template<class T>
T& deref(T& t){
return t;
}
template<class T>
T& deref(T*& t){
return *t;
}
, http://www.boost.org/doc/libs/1_44_0/libs/type_traits/doc/html/boost_typetraits/reference/is_pointer.html
?
, 我不知道这是否适合您的模式,但是对于成员函数引用,boost :: bind和boost :: phoenix已经可以满足您的要求:
struct T
{
void f(int) const {}
};
T instance;
T* pointer = new T();
boost::shared_ptr<T> shared(new T());
boost::bind( & T:f,instance,1); // stores instance by value
boost::bind( & T:f,boost::ref(instance),2); // stores instance by ref
boost::bind( & T:f,boost::cref(instance),3); // stores instance by const ref
boost::bind( & T:f,pointer,4); // dereferences the pointer
boost::bind( & T:f,shared,5); // dereferences the smart pointer
_您甚至可以使用typetraits让boost :: bind / phoenix知道您自己的智能指针(或使用时要用operator *和operator->取消引用的任何类型)_