是否有办法检测混合类型和非类型的任意模板类

Is there any way of detecting arbitrary template classes that mix types and non-types?

本文关键字:类型 任意模 是否 检测 混合      更新时间:2023-10-16

是否有任何方法可以检测类是普通类型还是模板类型(元类型)的实例化,其中可能包含非类型参数?我想到了这个解决方案:

#include <iostream>
template <template<class...> class> 
constexpr bool is_template()
{
    return true;
}
template <class> 
constexpr bool is_template()
{
    return false;
}
struct Foo{};
template<class> struct TemplateFoo{};
template<class, int> struct MixedFoo{};
int main()
{
     std::cout << std::boolalpha;
     std::cout << is_template<Foo>() << std::endl;  
     std::cout << is_template<TemplateFoo>() << std::endl;  
     // std::cout << is_template<MixedFoo>() << std::endl; // fails here
}
但是,对于混合了非类型和类型的模板,如 ,它将失败。
template<class, int> struct MixedFoo{};

我不能提出任何解决方案,除非我必须显式地指定重载中的类型。当然,由于组合爆炸,这是不合理的。

相关问题(不是欺骗):是否有可能仅通过标识符检查成员模板的存在?

不,没有。

注意模板类本身并不是类。它们是类的模板

我想这是不可能的。

无论如何,你可以用另一种方法,让N被推导出来:

template<class, class> struct MixedFoo;
template<class C, int N> struct MixedFoo<C, std::integral_constant<int, N>>{};

现在,它返回true如预期:

 std::cout << is_template<MixedFoo>() << std::endl; // fails here

当然,你将不能再使用MixedFoo作为MixedFoo<int, 2>,所以我不确定它是否值得。