用Lambda初始化constexpr变量

4
#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)上编译没有任何问题。

2
请查看此问题的第二个答案。似乎这个变化与采用N4487有关。 - undefined
我喜欢的g++版本是clang。 - undefined
所以gnu的g++表现不正常?clang会出现预期失败吗? - undefined
1个回答

0
你需要调用lambda函数:
constexpr auto fx = [] (std::string msg) { return msg + "!\n"; }**()**;

这个背景不支持这种解释(而且你需要一个参数和C++20来实现)。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接