问题描述
我试图创建一个Tensor类(对于那些不知道这是一个多维数组的数学等价),我希望只允许它编译如果实例化的类型满足某种类型
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...
};
但是,由于变量模板参数 Sizes,所以这不起作用。 ..
。我希望能够实例化 CTensor
对象,如下所示:
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
最好的方法是什么?
推荐答案
为什么在类上使用 enable_if
它的目的是使功能在过载查找期间不出现。如果所有你想做的是断言某些条件总是满足,使用 static_assert
。
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");
};
这篇关于如何使用std :: enable_if与variadic模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!