在自己的成员函数中构造类时,如何强制类模板参数推导?
问题描述:
考虑以下代码:
struct A {};
template <typename T> struct B
{
B(T) {}
auto foo() {return B(A{});} // error: no matching function for call to 'B<int>::B(A)'
};
auto foo() {return B(A{});} // compiles
int main()
{
foo();
B b(0);
b.foo();
}
我理解为什么 B :: foo( )
无法编译:在 struct B< T>
, B
中(如除非明确将其用作模板,否则表示 B< T>
。
I understand why B::foo()
doesn't compile: Inside of struct B<T>
, B
(as an injected-class-name) means B<T>
unless it's explicitly used as a template. Which in this case prevents class template argument deduction.
让我们说我不能做 auto foo(){返回B< A>(A {});}
,因为我的实际代码依赖于用户提供的精心制作的推导指南。
Let's say I can't do auto foo() {return B<A>(A{});}
since my actual code relies on slightly elaborate user-provided deduction guides.
问题是:如何强制上课在 B :: foo
内构造 B
时的模板参数推导?
The question is: How do I force class template argument deduction when constructing B
inside of B::foo
?
我希望我不会缺少明显的东西。
答
您有资格这样做
auto foo() {return ::B(A{});}