简体   繁体   English

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

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

Consider following code:考虑以下代码:

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();
}

Try it live现场试玩

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.我理解为什么B::foo()不能编译:在struct B<T>B (作为注入的类名)意味着B<T>除非它明确用作模板。 Which in this case prevents class template argument deduction.在这种情况下,这会阻止类模板参数推导。

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.假设我不能执行auto foo() {return B<A>(A{});}因为我的实际代码依赖于稍微复杂的用户提供的推导指南。

The question is: How do I force class template argument deduction when constructing B inside of B::foo ?问题是:在B::foo内部构造B时,如何强制类模板参数推导?

I hope I'm not missing something obvious.我希望我没有遗漏一些明显的东西。

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

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

Another option is to use a function to do the type deduction for you.另一种选择是使用函数为您进行类型推导。

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

and use并使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM