考虑以下代码:
template <typename T>
class B
{
};
template <typename T>
B<T> f(T& t)
{
return B<T>();
}
class A
{
class C {};
C c;
public:
A() {}
decltype(f(c)) get_c() const { return f(c); }
};
int main()
{
A a;
a.get_c();
}
当我尝试编译它时,出现错误:
test.cpp: In member function 'B<A::C> A::get_c() const':
test.cpp:31:46: error: conversion from 'B<const A::C>' to non-scalar type 'B<A::C>' requested
似乎在 decltype 中,编译器不知道这是一个 const 成员函数,因此 c
类型为 const C
, 结果错误地推断出 f(c)
的类型成为B<C>
而不是 B<const C>
这就是事实。
是我做错了什么,还是编译器错误?我使用 gcc 4.6,但 4.4 和 4.5 表现出相同的行为。
最佳答案
编译器根据当前的 C++0x WP 正确运行。参见 this issue report ,目前正在研究中。
可能最终的 C++0x 标准不会改变您的 decltype
应用程序在函数名称之前的返回类型中的含义。您需要使用 ->decltype(f(c))
将其移动到参数列表之后,这有望在最终的 C++0x 中做正确的事情。
关于C++0x decltype 推导成员变量常量失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4938440/