0xb*_*00d 4 c++ templates operators type-traits
template<typename T>
struct foo
{
T* p;
foo(T* x) : p(x) {}
~foo() { if(p) delete p; }
T& operator*() const { return *p; }
};
int main()
{
foo<int> i(new int);
foo<void> v(new int); // <= illegal use of type 'void'
}
Run Code Online (Sandbox Code Playgroud)
如果T = void,那么我不想实现运算符*().我怎样才能做到这一点?我不想专门化这个类,因为我班上还有很多其他的方法.
PS:请注意,这只是解释我的问题的一个例子.
您可以将所有其他方法(与之配合使用T==void)移动到基类中并foo从中派生.然后foo可以专门为不申报operator*的T==void
template <typename T>
struct foobase {
T* p;
foobase(T* x) : p(x) {}
~foobase() { if(p) delete p; }
};
template <typename T>
struct foo : foobase<T> {
T& operator*() const { return *p; }
};
template<>
struct foo<void> : foobase<void> {
};
Run Code Online (Sandbox Code Playgroud)
C++ 11标准解决了这个问题std::unique_ptr:
typename std::add_lvalue_reference<T>::type
operator*() const { return *p; }
Run Code Online (Sandbox Code Playgroud)