【发布时间】:2021-01-03 12:33:10
【问题描述】:
我有一个派生自特定模板实例的非模板类。像往常一样,必须在派生类的构造函数中初始化基类。我发现在调用构造函数时可以省略特定的模板参数:主要编译器(VC、g++、clang)接受它。这看起来很奇怪,因为类模板本身不是类名:
$ cat template-base.cpp && g++ --pedantic -o template-base template-base.cpp && ./template-base
template <int I>
struct T
{
T(int) {}
};
struct DT: public T<1>
{
// Note: T<1>(42) is possible but not necessary.
// T<2>(42) is an error ("T<2> is not a base class", which is correct).
DT(): T(42) {}
};
int main()
{
DT dt;
}
(Johannes Schaub 回答了this similar question,其中派生类本身也是一个模板。在这种情况下,模板参数是强制性的,尽管它在那里同样可以很好地扣除。)
为什么我可以在这里使用类名之类的模板名? T 不是类!
【问题讨论】:
标签: c++ templates initialization base-class