-1

I have the following code:

template <class B, class A>
class C {

    A m_a;

public:

    explicit C(A a) : m_a(a) {}

};

int main() {
    C<int>(16);
    return 0;
}

that can not be compiled. My purpose is to automatically deduce class A using the constructor parameter but use manually mentioned class B. Is it possible?

1 Answers1

3

Sure, but only with a helper function.

As currently written, C<int> has to be the complete name of a type, which it obviously isn't. The constructor argument isn't considered until after the type of the object is determined.

So write

template <class B, class A>
C<B,A> make_c(A a) { return C<B,A>{a}; }

int main() {
    auto c = make_c<int>(16);

and now you have a function template whose second type parameter can be deduced as you want, from the argument, before you have to write out the type it returns.

Useless
  • 64,155
  • 6
  • 88
  • 132
  • So the difference is that partial arguments deduction is ok for usual function and not for the constructor? – Кирилл Волков Aug 22 '22 at 13:52
  • 1
    You can't invoke the constructor until you know the type you're constructing, so the type you're constructing can't depend on the the constructor. It's a circular dependency. Having a separate function just breaks this loop. – Useless Aug 22 '22 at 13:54