[英]variable no of arguments for class template's member function
我只是在學習模板,並試圖為像這樣的向量編寫一個簡單的模板 class
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 但沒有找到任何方法。 這可以通過專門化模板 class 來針對 N 的某些值完成,但是對於任意數量的 N 怎么辦?
您可以使用可變參數模板:
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>>;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.