C++模板可变但静态
我正在训练我的 C++ 模板技能,并且想要实现一个向量类。 该类由向量维度 N 和类型 T 定义。 现在我想要一个构造函数,它恰好接受 N 个 T 类型的变量。 但是我不知道如何告诉可变参数模板只接受 N 个参数。也许这可以通过模板专门化来实现? 还是我的思考方向错误? 对此的任何想法/想法将不胜感激。
更多想法
我已经看到的所有关于可变参数模板的示例都使用递归来“迭代”参数列表。但是我记得构造函数不能从构造函数调用(阅读答案中的注释)。那么也许甚至不可能在构造函数中使用可变参数模板?无论如何,这只会让我推迟使用具有相同基本问题的工厂函数。
I am training my template skills in C++ and want to implement a vector class.
The class is defined by the vector dimension N and the type T.
Now I would like to have a constructor that takes exactly N variables of type T.
However I can't get my head around how to tell the variadic template to only accept N parameters. Maybe this is possible with template specialization?
Or am I thinking in the wrong direction?
Any thoughts/ideas on this would be greatly appreciated.
More thoughts
All examples on variadic templates I already saw used recursion to "iterate" through the parameter list. However I have in mind that constructors can not be called from constructors (read the comments in the answer). So maybe it is not even possible to use variadic templates in constructors? Anyway that would only defer me to the usage of a factory function with the same basic problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
可变参数构造函数似乎很合适:
此示例使用完美转发和 static_assert 来生成硬错误,如果
Size
参数传递给构造函数的参数不准确。这可以调整:sizeof...(U) <= Size
,让剩余元素进行值初始化,T
,或完全匹配,例如T const&
;将违规转变为硬错误(再次使用static_assert
)或软错误(再次使用 SFINAE)A variadic constructor seems appropriate:
This example uses perfect forwarding and and
static_assert
to generate a hard-error if not exactlySize
arguments are passed to the constructor. This can be tweaked:std::enable_if
(triggering SFINAE); I wouldn't recommend itsizeof...(U) <= Size
, letting the remaining elements to be value initializedT
, or exactly match e.g.T const&
; either turning a violation into a hard-error (usingstatic_assert
again) or a soft-error (SFINAE again)