我有关于嵌套模板和重写赋值运算符的问题。 假设我想要一个refcounting类模板_reference。现在这个_reference只是 包含一个指向ref-counting对象的指针。现在的问题是,这一切工作正常, 只要我用简单的类或结构做这个。例如。 _reference ...,嵌套模板中的运算符=(T * r)
但现在我想做一个类模板,它是一个std向量转发它所持有的类的引用。
不,我只是张贴代码:(它没有做引用计数和的东西,现在,它只是这个问题我已经提取)
template <typename T>
class _reference
{
private:
T* p_;
public:
// !!! this assignment seems only to work, when T is no class template already...
void operator= (T* r)
{
p_ = r;
}
// WHILE this ALWAYS works as well...
void simplySetIt (T* r)
{
p_ = r;
}
};
template <typename T>
class _ref_vector : public _reference<vector<T> >
{
};
void test2()
{
_reference<vector<long> > ref_ptr2;
_ref_vector<long> ref_ptr3;
ref_ptr2 = new vector<long>; // works fine.
ref_ptr3 = new vector<long>; // BUT: THIS doesnt work
ref_ptr3.simplySetIt (new vector<long>); // WHILE: this works fine...
}
MSVC错误:
error C2679: binary '=' : no operator found which takes a right-hand operand of type
'std::vector<_Ty> *' (or there is no acceptable conversion)
GCC-错误:
error: no match for 'operator=' in 'ptr3 = (((const stlp_std::allocator<long int>&)
((const stlp_std::allocator<long int>*)(& stlp_std::allocator<long int>()))),
(((stlp_std::vector<long int, stlp_std::allocator<long int> >*)operator new(12u)),
((<anonymous> != 0u) ? (<anonymous>->stlp_std::vector<_Tp, _Alloc>::vector [with
_Tp = long int, _Alloc = stlp_std::allocator<long int>]
(<anonymous>), <anonymous>) : <anonymous>)))'
所以,请有人解释为什么赋值运算符不能在这里工作,而简单的SetIt函数呢?
不要使用'_reference'等类名。在命名空间范围内以下划线开头的名称是为实现保留的。你冒着名字冲突的危险 – jalf 2009-10-26 09:41:33