【发布时间】: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 使用的本地自动存储持续时间变量。