Skip to content

Instantly share code, notes, and snippets.

@kikairoya
Created January 7, 2012 06:34
Show Gist options
  • Save kikairoya/1574004 to your computer and use it in GitHub Desktop.
Save kikairoya/1574004 to your computer and use it in GitHub Desktop.
#include <array>
#include <type_traits>
template <typename T, std::size_t N>
constexpr std::size_t size(const std::array<T, N> &a) { return a.size(); }
template <typename A> // テンプレートでなくても同じ
void f(const A &a) {
char x[a.size()]; // VLA扱いされる。std::array::size()はconstexprになっている
char y[size(a)]; // 一段噛ませると通る
static_assert(std::is_same<decltype(x), decltype(y)>::value, "");
}
int main() {
std::array<int, 4> a;
f(a);
}
// $ g++ test1.cc -std=c++0x -Wall -pedantic-errors
// test1.cc: In function ‘void f(const A&) [with A = std::array<int, 4ul>]’:
// test1.cc:16:6: instantiated from here
// test1.cc:9:8: error: ISO C++ forbids variable length array [-Wvla]
// test1.cc:16:6: instantiated from here
// test1.cc:10:17: error: ‘char [(((long unsigned int)(((long int)(& a)->std::array<_Tp, _Nm>::size [with _Tp = int, long unsigned int _Nm = 4ul, std::array<_Tp, _Nm>::size_type = long unsigned int]()) + -0x00000000000000001)) + 1)]’ is a variably modified type
// test1.cc:10:17: error: trying to instantiate ‘template<class, class> struct std::is_same’
#include <array>
#include <type_traits>
template <typename T, std::size_t N>
constexpr std::size_t size(const std::array<T, N> &a) { return a.size(); }
template <typename A>
void f(const A &a) { // 値渡しすると通る。この挙動は規格通りか?
std::array<char, a.size()> x; // error: 'a' is not a constant expression
std::array<char, size(a)> y; // こっちは期待通り通る
static_assert(std::is_same<decltype(x), decltype(y)>::value, "");
}
int main() {
std::array<int, 4> a;
f(a);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment