可以推断左值引用非类型模板参数吗?
Can an lvalue reference non-type template parameter be inferred?
我有以下代码,我无法开始工作:
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 &')
完全可能推断lvalue参考模板参数吗?如果可以,应该怎么做?
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 of A
differs from the type of i
, 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 of i
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已于去年解决。
我有以下代码,我无法开始工作:
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 &')
完全可能推断lvalue参考模板参数吗?如果可以,应该怎么做?
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已于去年解决。