#include <iostream>
#include <array>
int main(int argc, char **argv) {
constexpr const std::array<int, 2> arr {{ 0, 1 }};
constexpr const int arr2[] = { 0, 1};
static_assert(arr[0] == arr2[0], "asdf");
static_assert(arr[1] == arr2[1], "asdfasdf");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当编译gcc 4.8.2和4.9.1使用g++ test.cpp --std=c++11,编译成功.当编译clang 3.4和3.5利用clang++ test.cpp --std=c++11然而,编译失败:
test.cpp:8:16: error: static_assert expression is not an integral constant expression
static_assert(arr[0] == arr2[0], "asdf");
^~~~~~~~~~~~~~~~~
test.cpp:8:16: note: non-constexpr function 'operator[]' cannot be used …Run Code Online (Sandbox Code Playgroud) 我想创建一个由一些已知函数填充的2D数组,没有运行时开销.
有一个例子,假设一个功能f(x, y) = 10 * y + x,让x在{1, 2, 3}和y中{4, 5, 6}.我想创建一个包含内容的2D数组
41 42 43
51 52 53
61 62 63
Run Code Online (Sandbox Code Playgroud)
现在,最简单的方法就是直接在我的源代码中对值进行硬编码.这确实适合我的任务,所以问题只是出于好奇.
我想创建一个metafunc和结构具有某种魔法,这让我定义数组出给定值的集合的拥有x和y.像这样:
template<int X> struct Func {
template<int Y> struct over {
static const int value = 10 * Y + X; // f(x, y)
};
};
template<int... args1> struct Rows {
template<int... args2> struct Cols {
static const int data[sizeof...(args1)][sizeof...(args2)];
}; …Run Code Online (Sandbox Code Playgroud) 众所周知,std::array::operator[]自C++ 14以来constexpr,请参阅下面的声明:
constexpr const_reference operator[]( size_type pos ) const;
Run Code Online (Sandbox Code Playgroud)
但是,它也是const合格的.如果要使用a的下标运算符,std::array以便在编译时为数组赋值,则会产生影响.例如,考虑以下用户文字:
template<typename T, int N>
struct FooLiteral {
std::array<T, N> arr;
constexpr FooLiteral() : arr {} { for(int i(0); i < N; ++i) arr[i] = T{42 + i}; }
};
Run Code Online (Sandbox Code Playgroud)
如果您尝试声明constexpr类型的变量,则上述代码将无法编译FooLiteral.这归因于重载决策规则将数组下标运算符的非const限定非constexpr重载限定为更好的匹配.因此编译器抱怨调用非constexpr函数.
我无法弄清楚什么是为commitee宣布此重载为理由const胜任C++ 14,但似乎暗示被发现并还有一个建议p0107R0在upcomming C++ 17解决这个问题.
我自然而然地为C++ 14克服这个问题是为了唤起正确的下标运算符,以某种方式破解表达式.我做的是以下内容:
template<typename T, int N>
struct FooLiteral {
std::array<T, N> arr;
constexpr FooLiteral() : arr {} …Run Code Online (Sandbox Code Playgroud) 是否可以在编译时将 base64 编码数据解码为二进制数据?
我想到了这样的事情:
constexpr auto decoded = decodeBase64<"SGVsbG8=">();
或者
constexpr auto decoded = decodeBase64("SGVsbG8=");
我对生成的decoded.
c++ ×4
constexpr ×3
c++11 ×2
arrays ×1
c++14 ×1
c++17 ×1
compile-time ×1
const-cast ×1
stdarray ×1