是代码片段
struct Parameters {
static constexpr int n = 2;
static constexpr double v[n] = {4.0, 5.0};
};
Run Code Online (Sandbox Code Playgroud)
合法的C++ 11?并且,如果是这样,是Parameters::v[0]和Parameters::v[1]编译时间常量或只是指针Parameters::v本身a constexpr(无论在编译时意味着什么)?
正如您所看到的,我通常对constexpr数组及其在类/结构中的初始化感到困惑.请随时回答我的具体问题,并提及有关此主题的常见陷阱等.
Visual C++ 2017和gcc 5.4 在此代码段中产生但不是conversion from 'const unsigned char' to 'const float' requires a narrowing conversion警告:Line BLine A
#include <iostream>
int main() {
const unsigned char p = 13;
const float q = p; // Line A
std::cout << q << '\n';
const unsigned char c[3] = {0, 1, 255};
const float f[3] = {c[2], c[0], c[1]}; // Line B
for (auto x:f)
std::cout << x << '\n';
}
Run Code Online (Sandbox Code Playgroud)
这个警告有效吗?为什么Line B治疗不同于Line A?
我有一个名为access的constexpr函数,我想从数组中访问一个元素:
char const*const foo="foo";
char const*const bar[10]={"bar"};
constexpr int access(char const* c) { return (foo == c); } // this is working
constexpr int access(char const* c) { return (bar[0] == c); } // this isn't
int access(char const* c) { return (bar[0] == c); } // this is also working
Run Code Online (Sandbox Code Playgroud)
我收到错误:
error: the value of 'al' is not usable in a constant expression
Run Code Online (Sandbox Code Playgroud)
为什么我不能从访问中访问其中一个元素?或者更好我该怎么做,如果有可能的话?