我想static const char在班上有一个数组.海湾合作委员会抱怨并告诉我应该使用constexpr,虽然现在它告诉我这是一个未定义的参考.如果我使数组成为非成员,那么它将编译.到底是怎么回事?
// .hpp
struct foo {
void bar();
static constexpr char baz[] = "quz";
};
// .cpp
void foo::bar() {
std::string str(baz); // undefined reference to baz
}
Run Code Online (Sandbox Code Playgroud) 在下面的示例中,我可以从lambda内部访问constexpr变量x,y而无需显式捕获它.如果x未声明为,则无法执行此操作constexpr.
是否有适用constexpr于捕获的特殊规则?
int foo(auto l) {
// OK
constexpr auto x = l();
auto y = []{return x;};
return y();
// NOK
// auto x2 = l();
// auto y2 = []{ return x2; };
// return y2();
}
auto l2 = []{return 3;};
int main() {
foo(l2);
}
Run Code Online (Sandbox Code Playgroud) 在C++ 11和C++ 14中,为什么我需要constexpr在以下代码段中:
class Foo {
static constexpr double X = 0.75;
};
Run Code Online (Sandbox Code Playgroud)
而这个产生编译错误:
class Foo {
static const double X = 0.75;
};
Run Code Online (Sandbox Code Playgroud)
(更令人惊讶的是)这个编译没有错误?
class Foo {
static const double X;
};
const double Foo::X = 0.75;
Run Code Online (Sandbox Code Playgroud) 我实际上在Visual Studio 2017(Visual C++ 14.15.26706)上用C++ 17中的lambdas进行了一些测试.下面的代码非常有效.
#include <iostream>
int main()
{
bool const a_boolean { true };
int const an_integer { 42 };
double const a_real { 3.1415 };
auto lambda = [a_boolean, an_integer, a_real]() -> void
{
std::cout << "Boolean is " << std::boolalpha << a_boolean << "." << std::endl;
std::cout << "Integer is " << an_integer << "." << std::endl;
std::cout << "Real is " << a_real << "." << std::endl;
};
lambda();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是我的一个朋友在Qt Creator上测试了一个现代的MinGW,我也做了,我们都得到两个相同代码的警告而不是珍贵. …
结构C定义了几个静态const成员,如下所示:
代码如下:
#include<stdio.h>
struct C{
static int i;
static const int j=1;
static constexpr double d=1;
static const double d1=1.0;
};
int main(){
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译将导致错误:
$g++ testStatic.cpp -std=c++11
testStatic.cpp:6:25: error: in-class initializer for static data member of
type 'const double' requires 'constexpr' specifier
[-Wstatic-float-init]
static const double d1=1.0;
^ ~~~
testStatic.cpp:6:5: note: add 'constexpr'
static const double d1=1.0;
^
constexpr
1 error generated.
Run Code Online (Sandbox Code Playgroud)
为什么这么奇怪为什么static int可以是const?double应该是constexpr?
在C++ 14标准§5.1.2/ 12中,它显示了一个lambda表达式的示例,该表达式显然似乎能够引用到达范围的变量x,即使:
x"这是一个例子:
void f(int, const int (&)[2] = {}) { } // #1
void test() {
const int x = 17;
auto g = [](auto a) {
f(x); // OK: calls #1, does not capture x
};
}
Run Code Online (Sandbox Code Playgroud)
看它确实编译.它似乎取决于x存在const; 如果const删除它,它不再编译因为人们期望的原因(捕获列表为空).即使我将参数设置为int不再是通用lambda,也会发生这种情况.
x即使捕获列表为空,lambda如何引用?这怎么可能同时显然没有捕获x(如评论所说)?
我在这个问题上发现的最接近的事情就是其他人在评论中切实注意到这一点.
以下是标准中的完整部分5.1.2/12:
具有关联的capture-default的lambda表达式,它不显式捕获或具有自动存储持续时间的变量(这排除了任何已发现引用init-capture的关联非静态数据成员的id-expression),如果复合语句被称为隐式捕获 …