模板的实例化

Alb*_*ert 24 c++ templates

如果我有以下代码:

template <typename T = int>
struct mystruct {
  using doublestruct = mystruct<double>;
}

mystruct<>::doublestruct obj;
Run Code Online (Sandbox Code Playgroud)

这会实例化mystruct<int>模板吗?或者只是mystruct<double>实例化?

Mik*_*our 18

是的,它必须实例化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
Run Code Online (Sandbox Code Playgroud)


Lig*_*ica 16

是的,必须实例化; doublestruct是实例化的成员,所以如果你没有实例化,你就没有了doublestruct.

[C++11: 14.7.1]:除非已经显式实例化了类模板特化(14.7.2)或显式专用(14.7.3),否则在需要完全定义的对象类型或完整性的上下文中引用特化时,将隐式实例化类模板特化.类类型会影响程序的语义.[..]

特别是,考虑mystruct可能不包含成员的特化的潜在影响doublestruct,或者可能包含非类型的特化.