为什么包含标头会导致"use of auto before deduction of auto"错误?
Why does including a header cause a "use of auto before deduction of auto" error?
我把我正在做的项目缩短为三个简短的文件,复制正在发生的事情。我正在使用 2011 标准下的 g++ 使用 Code::Blocks IDE。
这些文件是main.cpp
、thing.cpp
和thing.h
。标头(.h
)有声明,源(.cpp
)有实现。thing
文件使用模板参数T
定义类Thing
。Thing
所做的只是保存一个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);
}
相关文章:
- Usages of std::move
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 使用 [] 运算符时"binding reference of type discards qualifiers"
- 如何处理 c++ 中类实现中的"invalid use of non-static data member"?
- 如何在自定义类中启用'auto loops'?
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 具有变量Number of Arguments的std::函数的矢量
- Capacity of a deque
- Deprecation of _writeBarrier()
- constexpr begin of a std::array
- 如何调整 std::vector of Eigen::MatrixXd 的大小
- C++ "error: invalid use of void expression"
- 我看到"use of undeclared identifier"错误,有人可以告诉我如何解决它吗?
- 赛通"Cannot take address of memoryview slice"
- C++ Version Of Double.longBitsToDouble
- 收到错误"invalid use of non-static data member 'stu::n' "
- C++ Usage of AsyncCallback
- 错误:"Left of getValue must have class/struct/union"
- 为什么包含标头会导致"use of auto before deduction of auto"错误?
- 使用"auto"关键字时"redefinition"错误更改为"differs in levels of indirection"