相关疑难解决方法(0)

为什么有状态但“constexpr” lambda 不能用作非类型模板参数?

不知何故,我仍然认为 lambda 是常规函数对象的“语法糖”,因此令我惊讶的是,在 C++-20 下,有状态但在其他方面的constexprlambda 实例不能用作非类型模板参数,这与等效的函数对象实例不同。

谁能解释这种行为或决定?

Godbolt示例:

struct always_fn {
    const int x;

    int operator()() const
    {
        return x;
    }
};
inline constexpr always_fn always_f{5};

// lambda equivalent to `always_f`
inline constexpr auto always_2_f = [x = 5]() {
    return x;
};

template<typename F>
struct wrapped {
    F f_;
};
inline constexpr auto wrapped_f = wrapped{always_f};
inline constexpr auto wrapped_2_f = wrapped{always_2_f};

template<auto f>
void pass() {}

int main() {
    pass<always_f>();
    pass<wrapped_f>();
    // error: no matching …
Run Code Online (Sandbox Code Playgroud)

c++ lambda constexpr c++20 non-type-template-parameter

5
推荐指数
1
解决办法
124
查看次数

将字符串文字传递给模板字符数组参数

CTRE库能够解析和使用类似语法在编译时验证的正则表达式ctre::match<"REGEX">(text_to_search)。我知道这种语法仅在 C++20 中受支持,这很好,但是无论我尝试什么,我都无法以这种方式使用字符串文字。这是一个非常简单的例子:

// The compiler refuses to pass string literals to STR in this compile time version.
template <char const STR[2]> constexpr int to_int_compile_time()
{
    return STR[0] - '0';
}

// It has no problems passing the string literal to str in this version.
int to_int_runtime(char const str[2])
{
    return str[0] - '0';
}
Run Code Online (Sandbox Code Playgroud)

调用to_int_runtime("0")工作正常,但to_int_compile_time<"0">()抱怨字符串文字不能用于此模板参数。应该如何to_int_compile_time编写才能将字符串文字传递到 char 数组模板参数中?

c++ string-literals compile-time constexpr c++20

4
推荐指数
1
解决办法
69
查看次数