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

时间:2016-10-02 00:32:51

标签: c++ templates c++11 c++14 typetraits

有没有办法检测某个类是普通类型还是模板类型(元类型)可能包含非类型参数?我提出了这个解决方案:

#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{};

我无法提出任何解决方案,除了我必须在重载中明确指定类型的解决方案。当然,由于组合爆炸,这是不合理的。

相关问题(不是欺骗):Is it possible to check for existence of member templates just by an identifier?

2 个答案:

答案 0 :(得分:4)

不,没有。

请注意,模板类本身不是类。它们是课程的模板。

答案 1 :(得分:1)

我想这是不可能的。

无论如何,你可以反过来使用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>了,所以我不确定它是否值得。