【问题标题】:Trouble with C++ templates (big surprise!). Why won't this work?C++ 模板的问题(大惊喜!)。为什么这行不通?
【发布时间】:2012-05-29 13:39:26
【问题描述】:

我正在测试一种模仿 C# 属性的方法,并创建了以下 property 类:

struct BY_REF
{
    template <class T>
    struct TT_s
    {
        typedef T &TT_t;
    };
};
struct BY_VAL
{
    template <class T>
    struct TT_s
    {
        typedef T TT_t;
    };
};

template <class T, class P=BY_REF>
class property
{
private:
    typedef typename P::template TT_s<T>::TT_t TT;
    T &value;
    property();
    property(const property &);
    property &operator=(const property &);
public:
    explicit property(T &v) : value(v) {}
    operator const TT() const
    {
        return value;
    }
    TT operator=(const TT i)
    {
        return value = i;
    }
};

我用以下代码测试了这个类:

int main()
{
    int i;
    std::string s;
    property<int, BY_VAL> I(i);
    property<std::string> S(s);
    //stringproperty S(s);
    I = 1337;
    char c[] = "I am ";
    S = std::string(c);
    cout << /*S <<*/ I << endl;
    return 0;
}

这给了我一个意外的编译器错误,“no match for 'operator='...”,对于行 S = std::string(c);。我把S的打印注释掉了,因为我operator=的问题似乎更简单,我希望它的解决方案也能解决operator&lt;&lt;的问题。为了弄清楚发生了什么,我手动实例化了模板,如下所示:

class stringproperty
{
private:
    std::string &value;
    stringproperty();
    stringproperty(const stringproperty &);
    stringproperty &operator=(const stringproperty &);
public:
    explicit stringproperty(std::string &v) : value(v) {}
    operator const std::string &() const
    {
        return value;
    }
    std::string &operator=(const std::string &i)
    {
        return value = i;
    }
};

我的手动版本有效。谁能解释为什么模板版本没有? (我怀疑它与 BY_REFBY_VAL 类有关,但我不知道为什么它适用于整数。)

【问题讨论】:

  • 属性类的头部有“#include ”表达式吗?
  • 错误可能是表达式的 const 部分吗? (例如const std::string &amp; != const TT)?

标签: c++ templates g++ operator-overloading overload-resolution


【解决方案1】:

您的手动版本有误,问题与模板无关。

typedef int& IntRef;

const int& == int const&

const IntRef == IntRef const == int& const

注意到区别了吗?因此问题就在那里:TT operator=(const TT i)

一般准则是,如果您想将typedef 视为简单的文本替换,那么您需要立即开始const 放在键入它的后面符合条件

【讨论】:

  • 手册版本实际上正是我想要的。如何修复模板版本以反映这一点?
  • 在任何情况下都将operator= 更改为T const&amp;。 (而且我还建议改变它的返回类型,感觉很奇怪,它不返回*this
  • 谢谢,我解决了这个问题。但现在我被ostream::operator&lt;&lt; 问题困住了。不知道是手动重载还是想办法让转换工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-21
  • 2012-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-12
相关资源
最近更新 更多