为什么包含标头会导致"use of auto before deduction of auto"错误?

Why does including a header cause a "use of auto before deduction of auto" error?

本文关键字:auto of before deduction 错误 包含标 为什么 use      更新时间:2023-10-16

我把我正在做的项目缩短为三个简短的文件,复制正在发生的事情。我正在使用 2011 标准下的 g++ 使用 Code::Blocks IDE。

这些文件是main.cppthing.cppthing.h。标头(.h)有声明,源(.cpp)有实现。thing文件使用模板参数T定义类ThingThing所做的只是保存一个T类型的对象(它基本上什么都不做)。

main.cpp

#include <iostream>
#include "thing.h"
int main(){
Thing<int> a(9);
Thing<double> b(3.2);
auto c = a + b;
c.display();
return 0;
}

thing.h

#ifndef THING_H
#define THING_H
template<typename T>
class Thing{
private:
T content;
public:
Thing(const T& content);
~Thing(){};
T get_content() const;
void display();
};
template<typename S, typename T>
auto operator+(const Thing<S>& s, const Thing<T>& t);
#endif // THING_H

thing.cpp

#include "thing.h"
#include <iostream>
template<typename T>
Thing<T>::Thing(const T& content)
:content(content){}
template<typename T>
void Thing<T>::display(){
std::cout << content << 'n';
}
template<typename T>
T Thing<T>::get_content() const {
return content;
}
template<typename S, typename T>
auto operator+(const Thing<S>& s, const Thing<T>& t){
S s_content = s.get_content();
T t_content = t.get_content();
Thing<typename std::common_type<S, T>::type> sum = s_content + t_content;
return sum;
}

这是一个奇怪的行为:代码将编译或不编译取决于行#include "thing.h"。在此处使用thing.h将无法编译,从而导致错误:

error: use of 'auto operator+(const Thing<S>&, const Thing<T>&) [with S = int; T = double]' before deduction of 'auto'
error: invalid use of 'auto'

将此行更改为#include "thing.cpp"允许代码编译没有问题并按预期运行(它12.2输出到控制台)。

我的问题是:在这两种情况下,编译器做了什么不同的事情?如何在includ标头时更改代码以消除此错误?

提前谢谢。

推导的返回类型是在 C++14 中引入的。

Coliru 在 C++11 模式下重现您的问题,但显示代码在 C++14 模式下工作。

当然,虽然这不是问题的直接原因,但您可能必须将模板定义移动到/a 标头中。

哦,这是您应该测试的最小测试用例:

template <typename T>
auto foo(T a)
{
return a;
}
int main()
{
foo(42);
}