【问题标题】:use of decltype(auto) <func> before deduction of auto [duplicate]在扣除 auto 之前使用 decltype(auto) <func> [重复]
【发布时间】:2018-08-20 11:59:51
【问题描述】:

以下情况:

#include <stdint.h>

class C
{
public:
    C()=default;
    ~C()=default;
    template<uint8_t> struct integconst
    {
    };

    int m1(integconst<8>);
    int m2(integconst<8>);
    decltype(auto) masterMethod(int opMode);
private:
};

int C::m1(integconst<8>) {return 1;}
int C::m2(integconst<8>) {return 2;}

decltype(auto) C::masterMethod(int opMode)
{
    switch(opMode)
    {
    case 1:
            return m1(integconst<sizeof(uintptr_t)>{}); break;
    case 2:
            return m2(integconst<sizeof(uintptr_t)>{}); break;
    default:
            return m1(integconst<sizeof(uintptr_t)>{}); break;
    }
}

int main()
{
    C obj;
    int bla=obj.masterMethod(1);
    return 0;
}

上面的简化示例将毫无问题地工作。但是当我尝试在单独的文件(full example here)中分离实现和声明时,我得到了错误

main.cpp: error: use of 'decltype(auto) C::masterMethod(int)' before deduction of 'auto'。将实现直接移动到类本身可以解决问题(或在同一个文件中实现方法),但我真的不明白为什么?有人可以解释一下为什么编译器还不知道 decltype(auto) 的类型,特别是编译器什么时候开始解析“auto”的返回类型?我想如何将实现和声明分开?

【问题讨论】:

  • 编译器需要定义函数来推断类型
  • @Tyker 但定义已经在 *.cpp 文件中?
  • 想象一下,您将这样的标头(没有此类方法的定义)包含到不同的 .cpp 文件中,该文件具有调用它的方法(如完整示例中的情况,您显示)。编译器应该如何决定 auto 在其他不包含定义的 .cpp 文件中应该解析为什么?
  • c++ 按翻译单元工作;并且彼此看不到其他人的内容。

标签: c++ c++14 auto decltype type-deduction


【解决方案1】:

每个源文件(.cpp 文件或.cc 文件)都必须独立存在。标准将这些文件称为翻译单元,因为程序的行为是相同的好像所有这些文件都作为单独的单元被翻译成机器语言,只有这样机器代码被链接到一个程序中。

“独立”意味着源文件连同其中包含的所有文件必须传达所有信息以翻译源文件。如果将masterMethod 放在一个源文件中,将main 放在另一个源文件中,则编译器在编译main 时不知道masterMethod 返回的类型。

你的问题的答案

如我所愿,如何将实现和声明分开?

就是这样:要么把函数的源代码放在头文件中,要么放弃使用返回类型推导。如果将源代码放到头文件中,则不需要将其放在类定义中,只要将其声明为内联即可。

【讨论】:

    【解决方案2】:

    如果您使用返回类型推导,则不能将声明及其定义分开到不同的文件中。在编译的时候,编译器必须能够知道'masterMethod'返回什么。

    我认为这类似于以下问题:

    `auto` return type in context of class members

    【讨论】:

      猜你喜欢
      • 2017-09-16
      • 1970-01-01
      • 2020-11-24
      • 1970-01-01
      • 1970-01-01
      • 2017-08-02
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      相关资源
      最近更新 更多