C++模板可变但静态

发布于 2024-12-09 14:48:00 字数 331 浏览 0 评论 0原文

我正在训练我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

预谋 2024-12-16 14:48:00

可变参数构造函数似乎很合适:

template<typename T, int Size>
struct vector {
    template<typename... U>
    explicit
    vector(U&&... u)
        : data {{ std::forward<U>(u)... }}
    {
        static_assert( sizeof...(U) == Size, "Wrong number of arguments provided" );
    }

    T data[Size];
};

此示例使用完美转发和 static_assert 来生成硬错误,如果 Size 参数传递给构造函数的参数不准确。这可以调整:

  • 您可以使用 std::enable_if (触发 SFINAE)将硬错误转换为软错误;我不建议
  • 您将条件更改为 sizeof...(U) <= Size,让剩余元素进行值初始化,
  • 您可以要求将类型传递给构造函数可转换为 T,或完全匹配,例如 T const&;将违规转变为硬错误(再次使用 static_assert)或软错误(再次使用 SFINAE)

A variadic constructor seems appropriate:

template<typename T, int Size>
struct vector {
    template<typename... U>
    explicit
    vector(U&&... u)
        : data {{ std::forward<U>(u)... }}
    {
        static_assert( sizeof...(U) == Size, "Wrong number of arguments provided" );
    }

    T data[Size];
};

This example uses perfect forwarding and and static_assert to generate a hard-error if not exactly Size arguments are passed to the constructor. This can be tweaked:

  • you can turn the hard-error into a soft-error by using std::enable_if (triggering SFINAE); I wouldn't recommend it
  • you can change the condition to be sizeof...(U) <= Size, letting the remaining elements to be value initialized
  • you can require that the types passed to the constructor are convertible to T, or exactly match e.g. T const&; either turning a violation into a hard-error (using static_assert again) or a soft-error (SFINAE again)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文