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.
You qualify it so that it's not the injected-class-name.
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{});}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With