Lala5th
Lala5th

Reputation: 1163

Why can't you specify template argument for constructor template

A while back I wanted to write a class that could return a pointer to a type, that was initialised with the same parameters all the time. As this only returns pointers, if I wanted to create an object returning A*, but generating B*, which is a child of A, there would not be an issue, as B* is castable to A*. I wanted to store these in a vector, but I didn't really care whether the generated type was B or C, only that it was a child of A. I wanted to do something like:

template<class RET_TYPE>
class Generator {
    public:
        template <class GEN_TYPE, class... Args> requires requires (Args...){
            { new GEN_TYPE(Args...) } -> std::convertible_to<RET_TYPE*>;
        }
        Generator (Args...) { /* Implementation */ }
        RET_TYPE getObject() { /* Implementation */}
};

The only issue is that as far as I found there is no way to specify the template parameters of the constructor. In the end I used a workaround, but I did not find a good explanation as to why this was the case. The most in detail I found one , talked about the constructor not actually possessing a name as such, but surely if that was the only issue it can be solved by: Generator<class template><Constructor template>(), no? The issue I see with this is name resolution, but it shouldn't be a problem, as it is unambiguous.

Upvotes: 1

Views: 183

Answers (1)

songyuanyao
songyuanyao

Reputation: 172934

This is the explanation from the standard, [temp.arg.explicit]/8:

[Note 4: Because the explicit template argument list follows the function template name, and because constructor templates ([class.ctor]) are named without using a function name ([class.qual]), there is no way to provide an explicit template argument list for these function templates. — end note]

And [class.ctor.general]/1:

Constructors do not have names.

Upvotes: 2

Related Questions