如果我有下面的代码:实例化模板
template <typename T = int>
struct mystruct {
using doublestruct = mystruct<double>;
}
mystruct<>::doublestruct obj;
这是否实例化mystruct<int>
模板呢?或者只有mystruct<double>
被实例化?
如果我有下面的代码:实例化模板
template <typename T = int>
struct mystruct {
using doublestruct = mystruct<double>;
}
mystruct<>::doublestruct obj;
这是否实例化mystruct<int>
模板呢?或者只有mystruct<double>
被实例化?
是的,它将不得不实例化mystruct<int>
以访问其成员并确定doublestruct
的含义。您可以使用static_assert
来测试:
#include <type_traits>
template <typename T = int>
struct mystruct {
static_assert(!std::is_same<T,int>::value, "");
using doublestruct = mystruct<double>;
};
mystruct<>::doublestruct obj; // assertion fails for T==int
mystruct<char>::doublestruct obj; // OK, not instantiated for int
mebe在这个演示中使用了“double”以外的东西;有点混淆 –
@LingningRacisinObrit:好的,我想。 –
是的,它必须实例化; doublestruct
是实例化的成员,因此,如果您没有实例化,则没有doublestruct
。
[C++11: 14.7.1]:
除非类模板特已经明确实例化(14.7.2)或明确专门(14.7.3),当专业化,需要一个completely-上下文引用的类模板专业化隐式实例定义的对象类型或类类型的完整性是否影响程序的语义。 [..]
特别是,考虑到可以不包含一个构件doublestruct
,或可含有一个不是一种类型的mystruct
特殊化的潜在影响。
您没有在模板中使用“T”类型。你想用这样的模板实现什么? –
@MykhayloKopytonenko:这是一个人为的例子。实际上,它是一个很好的测试用例。他询问一个模板是否仅在命名时指定了一个[非依赖]成员类型的实例。 –