【发布时间】:2019-03-27 19:19:00
【问题描述】:
我有以下代码:
template <class T>
class lit {
public:
lit(T l) : val(l) {}
T val;
};
template <class T>
class cat {
public:
cat(lit<T> const& a, lit<T> const& b) : a(a), b(b) {}
lit<T> const& a;
lit<T> const& b;
};
template <class T>
cat<T> operator+(lit<T> const& a, lit<T> const& b) {
return cat(a, b);
}
int main() {
auto r1 = cat((lit ('b')), lit('d')); // compiles
auto r2 = (lit ('b')) + lit('d') ; // doesn't compile
auto r3 = lit ('b') + lit('d') ; // compiles
auto r4 = (lit ('b')) ; // compiles
auto r5 = (lit<char>('b')) + lit('d') ; // compiles
}
使用 clang 可以很好地编译(正如我所料),但 gcc 会产生以下错误:
prog.cc: In function 'int main()':
prog.cc:23:20: error: missing template arguments after 'lit'
auto r2 = (lit ('b')) + lit('d') ; // doesn't compile
^~~
prog.cc:2:7: note: 'template<class T> class lit' declared here
class lit : public ExpressionBuilder<T> {
^~~
似乎只有在一种非常特殊的情况下(r2)才能从构造函数中找出类模板推导。我假设 gcc 是错误的,但有人可以解释为什么它只会在这种非常特殊的情况下失败吗?
【问题讨论】:
标签: c++ templates c++17 template-argument-deduction class-template