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

C++ 在自己的成员函数中构造类时,如何强制类模板参数推断?,c++,c++17,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);

考虑以下代码:

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();
}
struct A{};
模板结构B
{
B(T){}
auto foo(){return B(A{});}//错误:没有匹配的函数用于调用'B::B(A)'
};
auto foo(){返回B(A{});}//编译
int main()
{
foo();
B(0);
b、 foo();
}

我理解为什么
B::foo()
不编译:在
struct B
内部,
B
(作为注入类名)的意思是
B
,除非它被明确用作模板。在这种情况下,它阻止类模板参数推断

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

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


我希望我没有遗漏一些明显的东西。

您对其进行了限定,使其不是注入的类名

auto foo() {return ::B(A{});}

您可以限定它,使其不是注入的类名

auto foo() {return ::B(A{});}

另一个选项是使用函数为您进行类型推断

template <typename T> B<T> make_b(T t) { return B<T>(t); }

另一个选项是使用函数为您进行类型推断

template <typename T> B<T> make_b(T t) { return B<T>(t); }
::B(A{})
---<代码>::B(A{})---