且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

做一个static_assert一个模板类型的另一个模板

更新时间:2023-02-11 19:21:10

您可以做的东西沿着这些路线。给定一个特征,可以验证类是否是一个类模板的一个实例:

 的#include< type_traits>模板< typename的T,模板< typename的>一流的TT>
结构is_instantiation_of:性病:: false_type {};模板< typename的T,模板< typename的>一流的TT>
结构is_instantiation_of< TT< T&GT ;, TT> :性病:: true_type {};

在你的程序如下使用它:

 模板< typename的T>
结构foo的{};模板< typename的FooType>
结构bar {
  static_assert(is_instantiation_of< FooType,富> ::价值,失败);
};诠释的main()
{
    巴≤; INT> b: //错误!
    巴≤;富< INT>> b: // 好!
}

如果你愿意,你可以概括这个检测类是否是一个模板与任意数量的(类型)的参数,像这样一个实例:

 的#include< type_traits>模板<模板< typename的...>类TT,类型名T>
结构is_instantiation_of:性病:: false_type {};模板<模板< typename的...>类TT,类型名称... TS>
结构is_instantiation_of< TT,TT< TS ...>> :性病:: true_type {};模板< typename的FooType>
结构bar {
  static_assert(is_instantiation_of<富,FooType> ::价值,失败);
};

您会然后用它在你的程序是这样的:

 模板< typename的FooType>
结构bar {
  static_assert(is_instantiation_of<富,FooType> ::价值,失败);
};诠释的main()
{
    巴≤; INT> b: //错误!
    巴≤;富< INT>> b: // 好!
}

下面是一个live例如

How do I static_assert like this? Maybe Boost supports it if not C++ or new features in C++11?

template<T>
struct foo {};

template<FooType>
struct bar {
  static_assert(FooType is indeed foo<T> for some T,"failure"); //how?
};

You could do something along these lines. Given a trait that can verify whether a class is an instantiation of a class template:

#include <type_traits>

template<typename T, template<typename> class TT>
struct is_instantiation_of : std::false_type { };

template<typename T, template<typename> class TT>
struct is_instantiation_of<TT<T>, TT> : std::true_type { };

Use it as follows in your program:

template<typename T>
struct foo {};

template<typename FooType>
struct bar {
  static_assert(is_instantiation_of<FooType, foo>::value, "failure");
};

int main()
{
    bar<int> b; // ERROR!
    bar<foo<int>> b; // OK!
}

If you want, you could generalize this to detect whether a class is an instance of a template with any number of (type) parameters, like so:

#include <type_traits>

template<template<typename...> class TT, typename T>
struct is_instantiation_of : std::false_type { };

template<template<typename...> class TT, typename... Ts>
struct is_instantiation_of<TT, TT<Ts...>> : std::true_type { };

template<typename FooType>
struct bar {
  static_assert(is_instantiation_of<foo, FooType>::value, "failure");
};

You would then use it this way in your program:

template<typename FooType>
struct bar {
  static_assert(is_instantiation_of<foo, FooType>::value, "failure");
};

int main()
{
    bar<int> b; // ERROR!
    bar<foo<int>> b; // OK!
}

Here is a live example.