[英]Accepting nested variadic class templates as arguments to function template
[英]variadic templates same number of function arguments as in class
如何定义方法签名,以便它接受与variadic模板类定义相同数量的参数? 例如,如何定义Array类:
template<typename T, int... shape>
class Array
{
public:
T& operator () (???);
};
所以你可以像这样调用它:
Array<int, 3, 4, 5> a;
a(1, 2, 3) = 2;
template<class T, int...Shape>
class Array {
template<int>using index_t=int; // can change this
public:
T& operator()(index_t<Shape>... is);
};
要么:
template<class T, int...Shape>
class Array {
public:
T& operator()(decltype(Shape)... is);
};
要么:
template<class T, int...Shape>
class Array {
public:
T& operator()(decltype(Shape, int())... is);
};
如果您希望能够将参数的类型更改为与Shape
不同。
我发现decltype
比using
更难理解触摸,特别是如果你想要将参数的类型更改为不同于int
。
另一种方法:
template<class T, int...Shape>
class Array {
public:
template<class...Args,class=typename std::enable_if<sizeof...(Args)==sizeof...(Shape)>::type>
T& operator()(Args&&... is);
};
它使用SFINAE。 但是,它并不强制Args
是整数类型。 如果我们想要(我们可以将所有的Args
转换成int
,比如说),我们可以添加另一个子句。
另一种方法是让你的operator()
获取一个值包,比如std::array<sizeof...(Shape), int>
。 来电者必须:
Array<double, 3,2,1> arr;
arr({0,0,0});
使用一组{}
s。
最后的方法是:
template<class T, int...Shape>
class Array {
public:
template<class...Args>
auto operator()(Args&&... is) {
static_assert( sizeof...(Args)==sizeof...(Shapes), "wrong number of array indexes" );
}
};
我们接受任何东西的地方,如果是错误的参数数,则会产生错误。 这会产生非常干净的错误,但不能正确执行SFINAE运算符重载。
我建议使用标签调度,但是我没有看到比SFINAE解决方案更清晰的方法,另外一种方法是使用额外的decltype
以及所有或更好的错误消息而不是static_assert
版本。
我假设你希望你的参数都是相同的类型,可能使用整数类型(我只使用int
)。 一种简单的方法是利用您已有的参数包:
template <int>
struct shape_helper { typedef int type; };
template <typename T, int... Shape>
class Array
{
public:
T& operator()(typename shape_helper<Shape>::type...);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.