在自己的成员函数中构造类时,如何强制类模板参数推导?

Hol*_*Cat 11 c++ c++17

考虑以下代码:

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();
}
Run Code Online (Sandbox Code Playgroud)

Try it live

我理解为什么B::foo()不编译:内部struct B<T>,B(作为注入类名称)意味着B<T>除非它被明确地用作模板.在这种情况下,这会阻止类模板参数推断.

假设我不能这样做,auto foo() {return B<A>(A{});}因为我的实际代码依赖于用户提供的略微复杂的演绎指南.

问题是:在构造B内部时如何强制类模板参数推导B::foo

我希望我不会错过一些明显的东西.

T.C*_*.C. 21

你有资格使它不是注入类名.

auto foo() {return ::B(A{});}
Run Code Online (Sandbox Code Playgroud)