检查 class 是否属于模板特化(使用 bool 或 int 等模板参数)
Check if class is of template specialization (with template arguments like bool or int)
根据 and 的回答,我创建了以下变体来检查 MyClass1
、MyClass2
或 MyClass3
的特定实例:
template <class T, template <class...> class Template>
constexpr bool is_instance_of_v = false;
template <template <class...> class Template, class... Args>
constexpr bool is_instance_of_v<Template<Args...>, Template> = true;
template<class T> struct MyClass1 { };
template<class T, class B> struct MyClass2 { };
template<class T, bool B> struct MyClass3 { };
int main(int argc, char* argv[])
{
constexpr bool b1 = is_instance_of_v<MyClass1<float>, MyClass1>;
constexpr bool b2 = is_instance_of_v<MyClass1<float>, MyClass2>;
// constexpr bool b3 = is_instance_of_v<MyClass1<float>, MyClass3>; // <-- does not compile
return 0;
}
但是,b3
的代码无法编译并给出以下错误:
error C3201: the template parameter list for class template 'MyClass3' does not match the
template parameter list for template parameter 'Template'
error C2062: type 'unknown-type' unexpected
这似乎是因为 MyClass3
的 bool
参数不是 class
,因此无法通过 template <class...> class Template
.
捕获
有没有办法解决这个问题,使其适用于任何模板参数列表(不仅是 class
,还有 bool
、int
等)?
没有通用模板来处理类型参数和非类型参数(以及模板模板参数)。
根据 MyClass1
、MyClass2
或 MyClass3
的特定实例:
template <class T, template <class...> class Template>
constexpr bool is_instance_of_v = false;
template <template <class...> class Template, class... Args>
constexpr bool is_instance_of_v<Template<Args...>, Template> = true;
template<class T> struct MyClass1 { };
template<class T, class B> struct MyClass2 { };
template<class T, bool B> struct MyClass3 { };
int main(int argc, char* argv[])
{
constexpr bool b1 = is_instance_of_v<MyClass1<float>, MyClass1>;
constexpr bool b2 = is_instance_of_v<MyClass1<float>, MyClass2>;
// constexpr bool b3 = is_instance_of_v<MyClass1<float>, MyClass3>; // <-- does not compile
return 0;
}
但是,b3
的代码无法编译并给出以下错误:
error C3201: the template parameter list for class template 'MyClass3' does not match the
template parameter list for template parameter 'Template'
error C2062: type 'unknown-type' unexpected
这似乎是因为 MyClass3
的 bool
参数不是 class
,因此无法通过 template <class...> class Template
.
有没有办法解决这个问题,使其适用于任何模板参数列表(不仅是 class
,还有 bool
、int
等)?
没有通用模板来处理类型参数和非类型参数(以及模板模板参数)。