实现可变参数类型特征

Nik*_*iou 18 c++ templates generative-programming template-meta-programming c++11

介绍

我正在寻找一种模式将C++类型特征转换为它们的可变参数.一个方法来解决这个问题,将不胜感激,并生成编程模式,以自动执行任务将是理想的.

请考虑以下事项:

std::is_same<T, U>::value; 
Run Code Online (Sandbox Code Playgroud)

我想写一个像这样的特征:

std::are_same<T1, T2, T3, T4>::value; 
Run Code Online (Sandbox Code Playgroud)

目前的做法

实现这个非常简单are_same ; 寻求一般解决方案,我们可以为任何实现通用量化的可变特性提供工具:

template<template<class,class> class F, typename...Ts>
struct Univ;

template<template<class, class> class F, typename T, typename U, typename...Ts>
struct Univ<F, T, U, Ts...>
{
    static const int value = F<T, U>::value && Univ<F, U, Ts...>::value;
};

template<template<class, class> class F, typename T>
struct Univ<F, T>
{
    static const int value = 1;
};
Run Code Online (Sandbox Code Playgroud)

所以,例如are_same可以写成

Univ<is_same,int, int, int>::value
Run Code Online (Sandbox Code Playgroud)

而像创建特征时,这可能适用are_classes,are_scalars等等

泛化

小调整可以从前一个片段(替换为)中提供存在量化,以便我们以下列方式创建特征:&&||exist_same

Exist<is_same, int, double, float>::value
Run Code Online (Sandbox Code Playgroud)

以前关于类型特征的封面概括与

  • 主要类型类别
  • 复合类型类别
  • 输入属性
  • 支持的操作

我如何推广类型特征,如下所示:

    enable_if -> enable_if_any // enable if any clause is true
                 enable_if_all // enalbe if all clauses are true
                 enable_for    // enable only for the type provided
Run Code Online (Sandbox Code Playgroud)

exist_same上面例子过于简单了.任何正确实施的想法?

有type_traits "返回"修改后的类型.有关将这些扩展到任意数量类型的实现的建议吗?

是否有type_traits这些都使得不按比例来的类型参数任意号码

Dan*_*rey 23

我并不完全明白你想要达到的目标,但以下助手可能会有用,从以下开始bool_sequence:

#include <type_traits>

// Note: std::integer_sequence is C++14,
// but it's easy to use your own version (even stripped down)
// for the following purpose:
template< bool... Bs >
using bool_sequence = std::integer_sequence< bool, Bs... >;

// Alternatively, not using C++14:
template< bool... > struct bool_sequence {};
Run Code Online (Sandbox Code Playgroud)

接下来,您可以检查是否所有或任何布尔值或使用以下设置:

template< bool... Bs >
using bool_and = std::is_same< bool_sequence< Bs... >,
                               bool_sequence< ( Bs || true )... > >;

template< bool... Bs >
using bool_or = std::integral_constant< bool, !bool_and< !Bs... >::value >;
Run Code Online (Sandbox Code Playgroud)

它们派上用场,作为更高级和专业特性的基石.例如,您可以像这样使用它们:

typename< typename R, bool... Bs > // note: R first, no default :(
using enable_if_any = std::enable_if< bool_or< Bs... >::value, R >;

typename< typename R, bool... Bs > // note: R first, no default :(
using enable_if_all = std::enable_if< bool_and< Bs... >::value, R >;

typename< typename T, typename... Ts >
using are_same = bool_and< std::is_same< T, Ts >::value... >;
Run Code Online (Sandbox Code Playgroud)

  • +1`bool_sequence <(Bs || true)...>`是一个最方便的片段. (3认同)
  • @Yakk`(Bs,true)......`会导致某些编译器发出警告,这就是我使用`(Bs || true)...`的原因. (2认同)