【问题标题】:error: conversion from 'main()::<lambda()>' to non-scalar type 'function<void()>' requested错误:请求从 \'main()::<lambda()>\' 到非标量类型 \'function<void()>\' 的转换
【发布时间】:2022-12-17 13:35:08
【问题描述】:

在下面的 sn-p 中,我尝试将 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("Copy constructor invoked!\n");
    }

};

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

错误:

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

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

【问题讨论】:

  • ot:它不是复制构造函数。

标签: c++ lambda typetraits invocable


【解决方案1】:

您定义的模板错误。

您需要使用模板专业化。你也忘记了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!
");
    }

};

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

https://godbolt.org/z/xrvr3sMj3

您的版本必须这样使用:

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

https://godbolt.org/z/xvGd1s4az

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-01
    • 2019-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多