0

我正在测试一种模仿 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='...”,对于 line S = std::string(c);。我注释掉了打印,S因为我的operator=问题似乎更简单,我希望它的解决方案也能解决operator<<问题。为了弄清楚发生了什么,我手动实例化了模板,如下所示:

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_REFandBY_VAL类有关,但我不知道为什么它适用于整数。)

4

1 回答 1

4

Your manual version is erroneous, and the issue has nothing to do with templates.

typedef int& IntRef;

const int& == int const&

const IntRef == IntRef const == int& const

Notice the difference ? The issue is thus there: TT operator=(const TT i).

The general guideline is that if you want to treat a typedef as a simple text replacement, then you need to start right now: Put the const after the type it qualifies.

于 2012-05-29T13:51:21.893 回答