Skip to content

Instantly share code, notes, and snippets.

@dmikis
Created November 12, 2014 23:09
Show Gist options
  • Save dmikis/b196effb3ee26650b6f7 to your computer and use it in GitHub Desktop.
Save dmikis/b196effb3ee26650b6f7 to your computer and use it in GitHub Desktop.
static_assert for vector
#include <algorithm>
#include <array>
#include <initializer_list>
#include <iostream>
template <typename T, size_t N>
struct V
{
static_assert(N > 1, "V");
V(const std::initializer_list<T> & l) {
std::copy(l.begin(), l.end(), data_.begin());
}
T & x() {
static_assert(N > 0, "x");
return data_[0];
}
T & y() {
static_assert(N > 1, "y");
return data_[1];
}
T & z() {
static_assert(N > 2, "z");
return data_[2];
}
private:
std::array<T, N> data_;
};
int main() {
// если раскомментить, что будет ошибка компиляции
//V<float, 1> v1({1.0f});
V<float, 2> v2({1.0f, 2.0f});
std::cout <<
v2.x() << ' ' <<
v2.y() << ' ' <<
// если раскомментить, что будет ошибка компиляции
//v2.z() << ' ' <<
std::endl;
V<float, 3> v3({1.0f, 2.0f, 3.0f});
std::cout <<
v3.x() << ' ' <<
v3.y() << ' ' <<
v3.z() << ' ' <<
std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment