【问题标题】:variable no of arguments for class template's member function类模板的成员函数的变量无参数
【发布时间】:2020-05-09 13:15:47
【问题描述】:

我只是在学习模板,并试图为像这样的向量编写一个简单的模板类

template <unsigned N>
struct vec {
    std::array<float, N> m_buffer;

    float& operator[](unsigned index) { return m_buffer[index]; }

    vec(float value) {  std::fill(m_buffer.begin(), m_buffer.end(), value); }

    vec(float(&value)[N]) { std::copy(std::begin(value), std::end(value), std::begin(m_buffer)); }

    vec(float* value) {
        for (int i = 0; i < N; i++)
            m_buffer[i] = value[i];
    }

    float getmag() {
        float ret=0;
        for (int i = 0; i < N; i++)
            ret += m_buffer[N] * m_buffer[N];
        return sqrt(ret);
    }
};

int main() {    

    vec<3> a({ 1.0f, 2.0f, 3.0f });

    return 0;
}

现在我想创建一个构造器,它可以接收 N 个浮点数并将它们分配给数组 m_buffer,但没有找到任何方法。 这可以通过专门化模板类对 N 的某些值完成,但是对于任意数量的 N 怎么办?

【问题讨论】:

标签: c++ templates


【解决方案1】:

你可以使用可变参数模板:

template <unsigned N>
struct vec {
    std::array<float, N> m_buffer;

    template <typename ... Ts>
    vec(Ts... args) : m_buffer{{args...}} {}

// ...
};

可能会添加 SFINAE 以检查数量并限制为浮点可转换参数。

可能合适的替代方法是使用 index_sequence:

template <typename T, std::size_t>
using always_t = T;

template <typename Sequence> struct vec_seq;

template <std::size_t ... Is>
struct vec_seq<std::index_sequence<Is...>>
{
    static constexpr std::size_t N = sizeof...(Is);
    std::array<float, N> m_buffer;

    vec_seq(always<float, Iss... args) : m_buffer{{args...}} {}

// ...
};

template <std::size_t N>
using vec = vec_seq<std::make_index_sequence<N>>;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-09
    • 2017-10-18
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多