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

无人久伴 提交于 2019-12-30 08:07:22

问题


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. 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.

The question is: How do I force class template argument deduction when constructing B inside of B::foo?

I hope I'm not missing something obvious.


回答1:


You qualify it so that it's not the injected-class-name.

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



回答2:


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


来源:https://stackoverflow.com/questions/51754612/how-to-force-class-template-argument-deduction-when-constructing-a-class-in-its

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!