简体   繁体   中英

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.

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... . I wish to be able to instantiate the CTensor object as follows:

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

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 ? This is not what it is meant to be used for (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");
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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