C++0x decltype 推导成员变量常量失败

标签 c++ constants c++11 decltype

考虑以下代码:

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/

相关文章:

c++ - 当 this 实例化为 const 时抛出异常

php - 如何获取常量的名称?

c++ - 使用模板参数的 typedef 不适用于 g++

linux - 使用 message_queue 进行双向消息传递时 boost.interprocess 的问题

c++ - 如何使用 openSSL C++ 以 PEM 格式存储 Diffie HellMan 对象的 key

c++ - 在 OpenCV C++ 中估计基本矩阵之前标准化对应点的正确方法是什么?

c++ - 将仿函数而不是函数传递给 STL 是否仍然可取?

c++ - 使用 Matlab Coder 将 Matlab m 文件转换为 C/C++ 代码,包括 mex 文件 (mxArray)

c++ - 编译器使用了错误的函数原型(prototype)?

algorithm - 在没有循环的情况下向向量的所有条目添加一个值