访问前 n 个可变参数函数参数
我有以下代码:
template<size_t sz,typename T=float> class Vec{
T v[sz];
Vec(const T& val,const T&... nv){
//how do i assign `sz` number of first arguments into `this->v` array
}
}
我想创建构造函数,它接收构造函数参数的通用数量,并将第一个 sz
数量的参数分配给
我想要的 v
的成员变量要做的就是能够这样做:Vec<3> var(1.0,2.0,3.0);
I have the following code :
template<size_t sz,typename T=float> class Vec{
T v[sz];
Vec(const T& val,const T&... nv){
//how do i assign `sz` number of first arguments into `this->v` array
}
}
I want to create constructor, that receive generic number of constructor argument, and assign the first sz
number of arguments into member variable of v
what I want to do, is to be able doing like this: Vec<3> var(1.0,2.0,3.0);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
这是可能的,但很复杂。这是一些执行此操作的代码。也许可以消除
holder
类型,但我将其留给读者作为练习。这已经用 g++ 4.6 进行了测试。This is possible, but complicated. Here is some code that does it. It may be possible to eliminate the
holder
type, but I leave that as an exercise for the reader. This has been tested with g++ 4.6.我相信这满足了所有要求:
I believe this satisfies all the requirements:
这是另一种技术,如果可以至少不具有 sz 参数,则该技术要简单得多:
This is another technique which is much simpler if it is ok not to have at least sz parameters:
首先声明这个实用函数:
然后,在你的类中:
First declare this utility function:
Then, in your class:
sz
是一个模板参数,您可以直接在代码中使用它。sz
is a template argument, you can directly use it in your code.以下可以工作:
用法:
这允许您从任何可转换为
T
的内容构造数组元素。您可以使用sizeof...(Args)
获取参数的数量(可以是不超过N
的任何值)。The following could work:
Usage:
This allows you to construct the array elements from anything that's convertible to
T
. You can obtain the number of parameters (which can be anything not exceedingN
) withsizeof...(Args)
.你能利用这样的东西吗?
有一些规则可以限制您:
template...Args
样式的打包参数列表,Can you make use of something like this?
There are a few rules to constrain you:
template... Args
-style packed argument list per template class您需要在保持计数的同时解压参数包,并在函子中执行必要的运行时操作。这应该可以帮助您开始:
You need to unpack the argument pack while keeping a count and do the necessary runtime operation in a functor. This should get you started:
以下几乎有效(并且对于最后 N个参数而不是第一个,但是嘿)。也许有人可以帮助解决下面评论中的编译错误:
我不明白为什么它不明确,因为 0 比 N 更专业,所以应该满足部分顺序?!?!?
相比之下,下面的就很好了。
有什么区别?
The following almost works (and for the last N arguments instead of the first, but hey). Perhaps someone can help with the compile error in the comments below:
I don't see why it's ambiguous because 0 is more specialised than N so that should satisfy the partial order ?!?!?
By contrast, the below is fine.
What's the difference?