简体   繁体   English

如何在可变参数模板中使用std :: enable_if

[英]How to use std::enable_if with variadic template

I am trying to create a Tensor class (for those who don't know this is the mathematical equivalent of a multi-dimensional array), and I wish to only allow it to compile if instantiated with a type which satisfies certain type-traits. 我正在尝试创建一个Tensor类(对于那些不知道这与多维数组在数学上等效的类),并且我只希望在使用满足某些类型特征的类型实例化时才允许对其进行编译。

Ordinarily, I would do something like: 通常,我会做类似的事情:

template <typename T, std::size_t Size, typename Enable = void>
class Foo;

// Only allow instantiation of trivial types:
template <typename T, std::size_t Size>
class Foo<T, Size, typename std::enable_if<std::is_trivial<T>::value>::type>
{
     // Implement stuff...
};

However, I require an unknown number of template parameters to specify the bounds of each dimension of my tensor object like follows: 但是,我需要未知数量的模板参数来指定张量对象的每个维度的范围,如下所示:

template <typename T, std::size_t... Sizes, typename Enable = void>
class CTensor;

template <typename T, std::size_t Sizes>
class CTensor<T, Sizes..., typename std::enable_if<std::is_trivial<T>::value>::type>
{
     // Implement stuff...
};

However, this doesn't work due to the variadic template parameter Sizes... . 但是,由于可变参数模板参数Sizes... ,因此无法使用。 I wish to be able to instantiate the CTensor object as follows: 我希望能够实例化CTensor对象,如下所示:

CTensor<int, 3, 4, 5> testTensor; // Compiles fine and produces a rank 3 tensor
CTensor<ComplexClass, 3, 4, 5> testTensor2; // Produces a compile-time error

What is the best way of achieving this? 实现此目标的最佳方法是什么?

Why would you use enable_if on a class? 为什么要在类上使用enable_if It's purpose is to make functions not appear during overload lookup. 目的是使函数在重载查找期间不出现。 If all you want to do is assert that certain conditions are always met, use static_assert . 如果您要做的只是断言始终满足某些条件,请使用static_assert

template <typename T, std::size_t...Sizes>
class CTensor
{
     static_assert(std::is_trivial<T>::value, "T required to be a trivial type");
};

How about not using enable_if ? 不使用enable_if怎么样? This is not what it is meant to be used for (SFINAE). 这不是用于(SFINAE)的含义。 It appears that all you want to do is a static assert: 看来您要做的只是一个静态断言:

template <typename T, std::size_t... Sizes>
class CTensor
{
    static_assert(std::is_trivial<T>::value, "expecting trivial type blah blah");
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM