【问题标题】:Is there any way of detecting arbitrary template classes that mix types and non-types?有没有办法检测混合类型和非类型的任意模板类?
【发布时间】:2017-02-10 06:53:52
【问题描述】:

有什么方法可以检测一个类是普通类型还是模板类型(元类型)的实例可能包含非类型参数?我想出了这个解决方案:

#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?

【问题讨论】:

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


【解决方案1】:

不,没有。

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

【讨论】:

  • 是的,我知道模板类本身不是类型,而是元类型。尽管如此,人们还是可以将它们与普通类型区分开来,除非它们采用非类型参数。我想也许有人可以想出一个办法。
  • @vsoft 我添加了第二段,因为您的问题中有一个小错误(您将模板类称为类),但主要是因为第一段太短而无法回答。 ;)
【解决方案2】:

我想这是不可能的。

不管怎样,你可以反过来推导出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&lt;int, 2&gt;,所以我不确定是否值得。

【讨论】:

    猜你喜欢
    • 2018-12-05
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    • 2021-12-15
    • 2015-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多