#include <cstdint>
class MyBar {};
class DifferentBar {};
class Foo{
public:
template <class Bar = MyBar>
Foo(uint32_t i) {}
};
int main() {
auto pFoo1 = new Foo(3);
auto pFoo2 = new Foo<DifferentBar>(3);
}
我试图理解为什么编译器给我一个错误:
template_ctor.cpp: In function ‘int main()’:
template_ctor.cpp:14:19: error: ‘Foo’ is not a template
auto pFoo2 = new Foo<DifferentBar>(3);
^~~
是因为模板参数的默认参数只在类级别有效吗?当我改为:
template <class Bar = MyBar>
class Foo{
public:
Foo(uint32_t i) {}
};
它编译。</p>
提前致谢。
最佳答案
当你写作时
class Foo{
public:
template <class Bar = MyBar>
Foo(uint32_t i) {}
};
你说Foo
是具有模板构造函数的非模板类。
当你写作时
auto pFoo2 = new Foo<DifferentBar>(3);
你给Foo
模板参数;但是Foo
是一个非模板类。
所以错误。
改变 Foo
在具有默认参数模板的模板类中
<class Bar = MyBar>
class Foo{
public:
Foo(uint32_t i) {}
};
你现在有了new Foo<DifferentBar>(3);
是正确的,也可以编译 new Foo(3);
因为使用了默认模板参数 ( MyBar
)。
关于c++ - 模板参数的默认参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54388925/