[英]How to apply decltype to member function in declaration of operator[]
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
我试图让 smart_ptr 的operator []
与T::operator []
的返回类型一起工作,而无需明确指定int
返回类型。 但是,从上面可以明显看出,编译器无法编译代码。 如果有人可以帮助我,我将不胜感激。
看来您想要更好的编译器错误。 以下是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()
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.