【问题标题】:operator= (T *r) in nested templates嵌套模板中的 operator= (T *r)
【发布时间】:2010-12-10 01:30:40
【问题描述】:

我对嵌套模板和赋值运算符的覆盖有疑问。 假设我想要一个引用计数类模板_reference。这个 _reference 现在很简单 持有指向引用计数对象的指针。现在的问题是这一切都很好, 只要我用简单的类或结构来做这件事。例如。 _reference ...,

但是现在我想创建一个类模板,它是对转发它所拥有的类的标准向量的引用。

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

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>)))'

所以请谁能解释一下为什么赋值运算符在这里不起作用,而 simpleSetIt - 函数可以?

【问题讨论】:

  • 不要使用像_reference这样的类名。在命名空间范围内以下划线开头的名称保留用于实现。您冒着名称冲突的风险。

标签: c++ templates nested assignment-operator


【解决方案1】:

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

template <typename T>
class _ref_vector : public _reference<vector<T> >
{
  using _reference<vector<T> >::operator=;
};

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

【讨论】:

  • 太棒了 - 为我解决了这个问题:实际上我必须在 using 前面放一个 public: ,但现在它工作正常。谢谢马丁。
  • 啊是的 - 对:在 g++ 中它可以在没有公开的情况下工作。但是 msvc 开始抱怨没有。
【解决方案2】:

正如标准所说的 (13.5.3):

因为复制赋值运算符 operator= 被隐式声明为 如果用户没有声明一个类(12.8),一个基类赋值 操作符总是被复制赋值操作符隐藏 派生类。

【讨论】:

    猜你喜欢
    • 2019-03-23
    • 1970-01-01
    • 2015-02-20
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多