嵌套模板中的operator =(T*r)

Rom*_*udl 2 c++ templates nested assignment-operator

我有一个关于嵌套模板和赋值运算符重写的问题.假设我想要一个引用计数类模板_reference.这个_reference现在只是保存一个指向ref-counting对象的指针.现在的问题是,只要我使用简单的类或结构进行此操作,这一切都可以正常工作.例如._reference ...,

但是现在我想创建一个类模板,它是对std-vector的引用,它转发了它所拥有的类.

不,我只是发布代码:(它现在没有做引用和那些东西,它只是提取我​​遇到的问题)

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...
}
Run Code Online (Sandbox Code Playgroud)

MSVC错误:

error C2679: binary '=' : no operator found which takes a right-hand operand of type 
'std::vector<_Ty> *' (or there is no acceptable conversion)
Run Code Online (Sandbox Code Playgroud)

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>)))'
Run Code Online (Sandbox Code Playgroud)

那么请任何人解释一下为什么赋值运算符在这里不起作用,而simpleSetIt - 函数呢?

Mar*_*wis 6

基本运算符=被隐式赋值运算符隐藏,因此它不再参与重载.你需要写_ref_vector

template <typename T>
class _ref_vector : public _reference<vector<T> >
{
  using _reference<vector<T> >::operator=;
};
Run Code Online (Sandbox Code Playgroud)

由于没有编译器添加的simpleSetIt版本,查找将在基类中找到它.