由模板参数固定的C ++函数参数数量 [英] C++ number of function's parameters fixed by template parameter

查看:91
本文介绍了由模板参数固定的C ++函数参数数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的模板类:

I have a template class like this:

template <unsigned N>
class Pixel {
    float color[N];
}

我希望有一个精确的 N 参数来初始化类中的数组,如下所示:

I hope to have a constructor with exact N parameters to initialize the array in the class, like this:

Pixel<N> (float x_1, float x_2, ..., float x_N) {
    color[0] = x_1;
    color[1] = x_2;
    ...
}

很明显,我不能通过以下方式实现构造函数每个 N 手。那么,如何通过模板元编程或任何其他技术来实现这一目标呢?

Obviously I can't implement the constructor by hand for each N. So how can I achieve this goal by template metaprogramming or any other techniques?

推荐答案

其他答案很好,也很实用,但是这个问题很有趣,而做类似事情的背后技术可以为类似但更复杂和/或更实际的问题和解决方案提供良好的基础。以下是按照您描述的方式计算构造函数参数的内容:

The other answers are good and practical, but the question is interesting, and the technique behind doing something like that can form a good basis for similar, but more complicated and/or practical problems and solutions. Here's something that counts the constructor arguments the way you describe:

template <unsigned int N>
class Pixel {
public:
    template<typename... Floats> //can't use float... anyway
    Pixel(Floats&&... floats) : color{std::forward<Floats>(floats)...} {
        static_assert(sizeof...(Floats) == N, "You must provide N arguments.");
    }

private:
    float color[N];
};

int main() {
    Pixel<3> p(3.4f, 5.6f, 8.f);   
    Pixel<3> p2(1.2f); //static_assert fired
}

这篇关于由模板参数固定的C ++函数参数数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆