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

How to force class template argument deduction when constructing a class in its own member functions?

本文关键字:何强制 参数 函数 成员 自己的      更新时间:2023-10-16

请考虑以下代码:

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>,除非它明确用作模板。在这种情况下,这可以防止类模板参数推断。

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

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

我希望我没有错过一些明显的东西。

你限定它,以便它不是注入的类名。

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

另一种选择是使用函数为您进行类型推断。

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

和使用

auto foo() {return make_b(A{});}