c++ - 错误 : conversion from 'main()::<lambda()>' to non-scalar type 'function<void()>' requested

标签 c++ lambda typetraits invocable

在下面的代码片段中,我尝试将 lambda 转换为我自己的函数对象,并使用基于 invocable_r 类型特征的概念对其进行约束。然而 gcc 拒绝它。

Demo

#include <concepts>
#include <cstdio>


template <typename Fn, typename R, typename... Args>
concept invocable_r = std::is_invocable_r<R, Fn, Args...>::value;

template <typename R, typename... Args>
class function
{
    template <invocable_r<R, Args...> Cb>
    function(Cb fn) {
        printf("Converting constructor invoked!\n");
    }

};

int main()
{
    function<void()> hello = [](){};
}

错误:

error: conversion from 'main()::<lambda()>' to non-scalar type 'function<void()>' requested

我似乎找不到问题所在。怎么了?

最佳答案

您定义的 function 模板错误。您的版本接受多个参数,当您希望有一个特定类型的参数时。

您需要使用模板特化。你也忘记了 public::

#include <concepts>
#include <cstdio>


template <typename Fn, typename R, typename... Args>
concept invocable_r = std::is_invocable_r<R, Fn, Args...>::value;

template <typename T>
class function;

template <typename R, typename... Args>
class function<R(Args...)>
{
public:
    template <invocable_r<R, Args...> Cb>
    function(Cb fn) {
        printf("Copy constructor invoked!\n");
    }

};

int main()
{
    function<void()> hello = [](){};
}

https://godbolt.org/z/xrvr3sMj3

你的版本必须这样使用:

int main()
{
    function<void> hello = [](){};
}

https://godbolt.org/z/xvGd1s4az

顺便说一句,有 std::invocable概念,所以你介绍了一些 std 已经涵盖的东西。

关于c++ - 错误 : conversion from 'main()::<lambda()>' to non-scalar type 'function<void()>' requested,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74772606/

相关文章:

c++ - Qt中如何按区域填充不同颜色段的圆角矩形?

java - 对于 Java 8 中的 with 方法调用

javascript - 为什么不能使用lambda来定义原型(prototype)函数

c++ - 如何将二维数组的所有元素初始化为特定值?

c++ - 为什么我的预期输出没有发生?

java - 将一个 HashMap 缩减为另一个 HashMap

C++ std::variant - 类型特征以验证所包含的变体类型是否满足某些假设

c++ - 匹配成员函数存在和签名 : parameters

c++ - 我们应该序列化 std::chrono::duration 类还是 P.O.D. (普通旧数据)并且不需要序列化?

python - Boost Python - 用参数包装构造函数