How to use std::enable_if with variadic template

最后都变了- 提交于 2020-01-25 03:50:15

问题


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?


回答1:


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");
};



回答2:


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");
};


来源:https://stackoverflow.com/questions/24659013/how-to-use-stdenable-if-with-variadic-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!