我从另一段代码中遇到了这个问题,但归结为以下代码段:
#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;
}
这不会令人惊讶地引发以下错误:
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
^
这看起来像是以前会遇到一千次的问题,但我在 cppreference 或 SO 上找不到解决方案。
如何在新表达式中指定构造函数的模板参数?