是否可以编写以下代码?我想要做的是 do_vector_action 可以自动推导出函数的正确返回类型(我实际拥有的代码在 cpp 文件中定义了该函数,而不是在头文件中定义)。

class some_class
{
    public:
        std::vector<int> int_vector;
        auto do_vector_action() -> decltype(int_vector_.size())
        {
            decltype(int_vector.size()) something + 1;
            return something;
        }
}

此外,我还想知道,是否可以替换诸如
class some_class
{
    public:
        typedef std::vector<int> int_vector_type;
        int_vector_type int_vector;
        int_vector_type::size_type size;
}

使用 decltype 或其他一些构造,例如
  class some_class
  {
       public:
           std::vector<int> int_vector;
           decltype(int_vector)::size_type size;
  }

因为最后一个带有 decltype 的片段不能用 Visual Studio 2012 RC 编译。

最佳答案

decltype(int_vector.size()) something + 1;

这相当于:
std::vector<int>::size_type something + 1;

这是格式错误的(您正在声明一个名为 something 的变量,然后……向其中添加一个?

你的第二个例子,使用 decltype(int_vector)::size_type 是有效的。由于编译器错误 (*),Visual C++ 2010 和 2012 拒绝了它。作为一种解决方法,您应该能够将 size 声明为:
identity<decltype(int_vector)>::type::size_type size;

假设存在声明为的标准 identity 模板:
template <typename T>
struct identity { typedef T type; };

(*) 在 C++11 标准化过程即将结束时添加了在嵌套名称说明符中使用 decltype 的功能(请参阅 N3031 [PDF])。这是在 Visual C++ 2010 完成之后,并且在 Visual C++ 2012 中没有添加对此添加的支持。

关于c++ - 类头定义中的 Decltype 和 auto 是一些可能的特定情况,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11803719/

10-17 02:12