我有以下代码,我无法开始工作:
struct foo {};
foo foo1 = {};
template <foo& F>
class FooClass {};
template <foo& F>
void foobar(FooClass<F> arg) {
}
int main() {
FooClass<foo1> f;
foobar(f);
}
错误是:
main.cpp:14:5: error: no matching function for call to 'foobar'
note: candidate template ignored: substitution failure : deduced non-type template argument does not have the same type as the its corresponding template parameter ('foo' vs 'foo &')
可能推断左值引用模板参数吗?如果可以,应该怎么做?
最佳答案
CWG 2091 恰好涵盖了这一点:
According to 14.8.2.5 [temp.deduct.type] paragraph 17,
If
P
has a form that contains<i>
, and if the type of the corresponding value ofA
differs from the type ofi
, deduction fails.这给出了如下示例的错误结果:
template<int &> struct X; template<int &N> void f(X<N>&); int n; void g(X<n> &x) { f(x); }
在这里,
P
是X<N>
,其中包含<i>
.i
的类型是int&
. 对应的值来自A
是n
, 这是类型的左值int
.大概这应该是有效的。我认为这条规则的意思是说,
If
P
has a form that contains<i>
, and the type ofi
differs from the type of the corresponding template parameter of the template named by the enclosing simple-template-id, deduction fails.
如@dyp所述,[temp.deduct.type]/17应该更宽容。在您的示例中,FooClass<F>
中的参数( F
) 没有引用类型 - 它是 foo
类型的左值. FooClass
的模板参数是一个引用。 DR 已于去年解决。
关于c++ - 可以推断左值引用非类型模板参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35139955/