小编kla*_*ndl的帖子

为什么有状态但“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
查看次数