【问题标题】:constexpr lambda / ‘x’ does not name a type; did you mean ‘x’?constexpr lambda / ‘x’ 没有命名类型;你的意思是“x”吗?
【发布时间】:2016-11-02 07:06:49
【问题描述】:

我正在尝试使用 C++17 的 constexpr lambdas 来获取编译时字符串:

#include <utility>

template <char...>
struct str
{
  constexpr auto operator==(const str&) const { return true; }
  void foo() const;
};

template <typename S, std::size_t... Ns>
constexpr auto make_str(S s, std::index_sequence<Ns...>)
{
  return str<s()[Ns]...>{};
}

#define LIT(s) \
  make_str([]() { return s; }, std::make_index_sequence<sizeof(s) - 1>{})

constexpr auto x = LIT("hansi");
constexpr auto y = x;
static_assert(x == y);

目前看起来不错。但后来我尝试调用一个成员函数:

x.foo();

使用来自主干的当前 gcc (g++ (GCC) 7.0.0 20161102),我收到以下错误消息:

c.cpp:19:1: error: ‘x’ does not name a type; did you mean ‘x’?
 x.foo();

请参阅https://godbolt.org/g/uN25e1 以获取演示

因为我什至没有尝试使用 x 作为类型,这让我觉得很奇怪。

这是编译器错误吗?还是x 真的很奇怪?

【问题讨论】:

  • 你能链接到演示吗? godbolt.org/g/lWExfT 似乎有效
  • x.foo() 已添加。您需要在 main 中调用 x.foo()。 @Rumburak
  • 您的代码有一个隐藏的错误,因为sizeof(s) 可以产生指针的大小或char[N] 的大小。 Live demo
  • @ClaasBontus 在您的示例中,我想知道为什么 s 在 lambda 中是已知的?这不应该需要捕获吗?
  • @Rumburak, s 具有静态存储持续时间。没有必要捕捉它。捕获用于 this 和 ODR 使用的本地自动存储持续时间变量。

标签: c++ gcc c++17


【解决方案1】:

正如其他人在cmets中指出的那样,这只是调用函数命名空间范围的结果。

恕我直言,不过,错误消息非常模糊。

【讨论】:

    猜你喜欢
    • 2011-02-17
    • 1970-01-01
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-18
    • 2021-08-02
    • 1970-01-01
    相关资源
    最近更新 更多