【问题标题】:Is there a way using c++ type traits to check if a type is a template and any properties thereof?有没有办法使用 c++ 类型特征来检查类型是否是模板及其任何属性?
【发布时间】:2012-12-17 17:43:55
【问题描述】:

我希望能够推断给定类型是否是模板类型。我查看了 boost 的类型特征类,但找不到与模板相关的 is_* 特征: http://www.boost.org/doc/libs/1_52_0/libs/type_traits/doc/html/index.html

更有趣的是,如果在编译时有办法确定模板参数的属性,例如模板参数的数量或参数是否是模板模板参数。

【问题讨论】:

  • 如果你可以忘记 非类型模板参数,那么这是一件非常简单的事情,特别是在 C++11 中
  • @K-ballo:您仍然很难考虑模板模板参数...
  • type 绝不是模板类型!不过,它可能是模板实例化的结果,我想这就是你的意思。然而,问题是你为什么要关心?

标签: c++ templates typetraits


【解决方案1】:

这里是部分解决方案:

#include <iostream>
#include <type_traits>

template <typename> struct is_template : std::false_type {};

template <template <typename...> class Tmpl, typename ...Args>
struct is_template<Tmpl<Args...>> : std::true_type {};


template <typename> struct Foo {};

int main()
{
  std::cout << is_template<int>::value << std::endl;
  std::cout << is_template<Foo<char>>::value << std::endl;
}

问题在于模板可以具有任意结构,因此它不必只包含类型参数。您无法详尽地枚举所有种模板参数。

不过,只要坚持一分钟,就很容易得出一个论据反驳:

template <typename> struct nargs : std::integral_constant<unsigned int, 0> { };

template <template <typename...> class Tmpl, typename ...Args>
struct nargs<Tmpl<Args...> : std::integral_constant<unsigned int, sizeof...(Args)> { };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    相关资源
    最近更新 更多