在声明后对成员函数定义使用decltype
Using decltype with member function definitions after declaration
我使用decltype作为成员函数的返回类型,但定义和声明不匹配。这里有一些代码:
template<typename T>
struct A {
T x;
auto f() -> decltype(x);
};
template<typename T>
auto A<T>::f() -> decltype(x) {
return this->x;
}
int main() {}
这会产生
test.cc:10:6: error: prototype for 'decltype (((A<T>*)0)->A<T>::x) A<T>::f()' does not match any in class 'A<T>'
test.cc:6:7: error: candidate is: decltype (((A<T>*)this)->A<T>::x) A<T>::f()
不同之处在于定义具有CCD_ 1,其中声明具有(A<T>*)this
。什么东西?
这是我在这里报告的gcc 4.7中的一个错误:错误#54359(请参阅错误报告的底部)。gcc 4.6接受了这种特殊情况。
作为一种变通方法,不要使用尾随返回类型,而是直接使用成员x
的类型。在本例中,这只是T
,但您也可以转换更复杂的情况。例如,您可以转换:
T x;
auto f() -> decltype(x.foo);
进入:
T x;
decltype(std::declval<T>().foo) f();
std::declval在这里非常有用。
相关文章:
- 在提升multi_index容器中,是否定义了"default index"?
- #定义c-预处理器常量..我做错了什么
- 用C++中的一个变量定义一个常量
- 部分定义/别名模板模板参数
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- #为""定义宏;静态";针对不同的上下文
- 如何确保C++函数在定义之前声明(如override关键字)
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在命名空间中定义函数还是限定函数
- 是否可以在不使用 decltype 的情况下推断先前定义的 extern 变量的类型
- 是否可以使用单个定义定义函数的常量和常规版本?(使用模板,自动,decltype等)
- 为什么不允许通过 decltype(lamda) 定义对象,我该如何改进它?
- 类内定义函数的 decltype 推导结果
- 在声明后对成员函数定义使用decltype
- 如果我们使用 "decltype(auto) f()" 作为函数声明,定义中带有"decltype(f()) result",会发生什么?
- 使用decltype定义静态成员(Intellisense不同意)
- 'decltype':函数返回类型"T"转换为用户定义类型的"T&"(VS2010)
- 在类模板的可变函数模板上使用decltype定义成员变量
- 为什么decltype将变量定义为引用?