gcc 通过lambda初始化constexpr变量

30byixjq  于 2023-10-19  发布在  其他
关注(0)|答案(1)|浏览(124)
#include <iostream>
#include <string>

constexpr auto fx = [] (std::string msg) {
  return msg + "!\n"; };

int main(int argc, char* argv[]) {
  if (argc == 2)
    std::cout << "hello " << fx(argv[1]);
  else
    std::cout << "hello world!" << std::endl;
}

命令

$ g++ -o hello -std=c++11 hello.cpp

hello.cpp:4:21: error: constexpr variable 'fx' must be initialized by a constant expression
constexpr auto fx = [] (std::string msg) {
                    ^~~~~~~~~~~~~~~~~~~~~~
1 error generated.

g++版本:

$ g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 7.3.0 (clang-703.0.31)
Target: x86_64-apple-darwin15.6.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

在gcc版本5.2.1(Linux)上编译没有任何问题。

a5g8bdjr

a5g8bdjr1#

你需要调用lambda:

constexpr auto fx = [] (std::string msg) { return msg + "!\n"; }**()**;

相关问题