Search code examples
c++templatesnew-expression

How to specify constructor's template arguments inside a new expression?


This issue occurred to me from an other piece of code but it boils down to this snippet:

#include <iostream>

struct A
{
    template <int I>
    A() : _i{I} {}

    int _i;
};

int main()
{
    A* ptr = new A; // how to call the constructor with a specific template argument ?

    return 0;    
}

This will not surprisingly raise the following error:

clang++ -std=c++17 -Wall main.cpp && ./a.out;

main.cpp:13:18: error: no matching constructor for initialization of 'A'

    A* ptr = new A; // how to call the constructor with a specific template argument ?
                 ^
main.cpp:6:5: note: candidate template ignored: couldn't infer template argument 'I'

    A() : _i{I} {}
    ^
main.cpp:3:8: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 0 were provided

struct A
       ^

This looks like an issue that would have been encountered a thousand times before but I couldn't find the solution on cppreference or SO.

How to specify constructor's template arguments inside a new expression ?


Solution

  • Unfortunately, you can't specify template arguments explicitly for constructor template, which can't be used unless the template parameters could be deduced. [temp.arg.explicit]/8

    [ Note: 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 ]