如何将 decltype 应用于运算符 [] 声明中的成员函数
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]'
IDONE: 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()
)。
相关文章:
- 在指向现有内存地址的 hpp 文件中声明成员函数的最佳方法
- 如何使用模板声明成员函数?(不是模板类)
- 如何使用 Boost.Hana 声明成员变量
- 声明成员对象而不调用其默认构造函数
- 使用函数类型语法声明成员函数
- 尝试访问标头声明成员时出现隔离错误
- 根据二手构造函数声明成员
- C 模板明确声明成员函数值/避免了宏的问题
- 如何在基本模板类中声明成员,其中类型取决于派生类的类型
- 错误:类中没有声明成员函数
- 我可以使用相同的名称为周围作用域中的类型声明成员类型别名吗
- 从variadic模板参数声明成员变量
- 在类(C )中使用模板时未声明成员函数
- 错误:类中未声明 '' 成员函数
- 如何在指向常量地址时声明成员函数常量指针
- 何时以及为什么在堆C++上声明成员变量
- C++ 错误:未在范围内声明;成员函数
- 在不声明成员变量的情况下更改按钮颜色
- 错误 C2535:已定义或声明成员函数
- 当声明成员函数时,*New()是什么意思