【发布时间】:2020-02-29 23:38:08
【问题描述】:
给定以下模板结构:
template<typename T>
struct Foo {
Foo(T&&) {}
};
这样编译,T 被推导出为int:
auto f = Foo(2);
但这不能编译:https://godbolt.org/z/hAA9TE
int x = 2;
auto f = Foo(x);
/*
<source>:12:15: error: no viable constructor or deduction guide for deduction of template arguments of 'Foo'
auto f = Foo(x);
^
<source>:7:5: note: candidate function [with T = int] not viable: no known conversion from 'int' to 'int &&' for 1st argument
Foo(T&&) {}
^
*/
但是,Foo<int&>(x) 被接受。
但是当我添加一个看似多余的用户定义的推导指南时,它起作用了:
template<typename T>
Foo(T&&) -> Foo<T>;
如果没有用户自定义的推演指南,为什么T不能推演为int&?
【问题讨论】:
-
那个问题好像是关于模板类型比如
Foo<T<A>>
标签: c++ templates language-lawyer