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