如何在operator []的声明中将decltype应用于成员函数

时间:2012-11-28 00:44:05

标签: c++ templates c++11

template <typename T>
class smart_ptr
{
public:
    // ... removed other member functions for simplicity
    T* get() { return ptr; }

    template <typename U>
    auto operator [](U u) const -> decltype((*get())[u])
    {
        return (*get())[u];
    }

    template <typename U>
    auto operator [](U u) -> decltype((*get())[u])
    {
        return (*get())[u];
    }

/*
    // These work fine:

    template <typename U>
    int operator [](U u)
    {
        return (*get())[u];
    }

    template <typename U>
    int& operator [](U u)
    {
        return (*get())[u];
    }
*/
private:
    T* ptr;
};

struct Test
{
};

struct Test2
{
    int& operator [](int i) { return m_Val; }
    int operator [](int i) const { return m_Val; }

    int m_Val;
};

int main()
{
    smart_ptr<Test> p1;
    smart_ptr<Test2> p2;
    p2[0] = 1;
}

错误:

prog.cpp: In function 'int main()':
prog.cpp:55:9: error: no match for 'operator[]' in 'p2[0]'

ideone:http://ideone.com/VyjJ28

我正在尝试使用返回类型operator []使smart_ptr的T::operator []工作,而不明确指定int返回类型。但是,从上面可以明显看出,编译器无法编译代码。如果有人能帮助我,我会很感激。

1 个答案:

答案 0 :(得分:2)

看起来你想要更好的编译器错误。以下是clang对此来源的评论(嗯,它说的更多但是这描述了这个问题):

decltype.cpp: In instantiation of ‘class smart_ptr<Test>’:
decltype.cpp:53:21:   required from here
decltype.cpp:9:51:error: cannot call member function ‘T* smart_ptr<T>::get() [with T = Test]’ without object
     auto operator [](U u) const -> decltype((*get())[u])       
                                                   ^

问题的解决方法是在对象上调用get(),例如:

auto operator[](U u) const -> decltype((*this->get())[u])

(当然也要求const成员get()