为什么这个简短的模板代码片段有效?
why is this short snippet of template code valid?
根据标题,我不明白当has_type_struct<no_type>
肯定是一个无效类型时,下面的代码如何编译。
template<typename T>
using my_int = int;
struct no_type {};
template<typename T>
struct has_type_struct { using type = typename T::type; };
template<typename T>
using has_type_using = typename T::type;
int main() {
my_int<has_type_struct<no_type>> a; // why does this compile?
//my_int<has_type_using<no_type>>(); // this rightfully does not compile
return 0;
}
该程序有效,因为 has_type_struct<no_type>
未实例化。
Unless a class template specialization has been explicitly instantiated or explicitly specialized, the class template specialization is implicitly instantiated when the specialization is referenced in a context that requires a completely-defined object type or when the completeness of the class type affects the semantics of the program.
my_int<has_type_struct<no_type>>
的使用不需要has_type_struct<no_type>
是完整的,因此后者没有实例化,也没有检查其定义中依赖名称的有效性。
根据标题,我不明白当has_type_struct<no_type>
肯定是一个无效类型时,下面的代码如何编译。
template<typename T>
using my_int = int;
struct no_type {};
template<typename T>
struct has_type_struct { using type = typename T::type; };
template<typename T>
using has_type_using = typename T::type;
int main() {
my_int<has_type_struct<no_type>> a; // why does this compile?
//my_int<has_type_using<no_type>>(); // this rightfully does not compile
return 0;
}
该程序有效,因为 has_type_struct<no_type>
未实例化。
Unless a class template specialization has been explicitly instantiated or explicitly specialized, the class template specialization is implicitly instantiated when the specialization is referenced in a context that requires a completely-defined object type or when the completeness of the class type affects the semantics of the program.
my_int<has_type_struct<no_type>>
的使用不需要has_type_struct<no_type>
是完整的,因此后者没有实例化,也没有检查其定义中依赖名称的有效性。