【问题标题】:Concatenate function calls with a template lambda C++20使用模板 lambda C++20 连接函数调用
【发布时间】:2021-06-22 05:55:27
【问题描述】:

我有一个连接函数调用的模板函数:

template<typename Callable, typename... Callables>
decltype(auto) concat_callable(Callable callable, Callables... callables)
{
    if constexpr (sizeof...(callables) > 0) {
        return [=]
        <typename... Args>
        (Args&&... args) {
            return callable(concat_callable(callables...)(std::forward<Args>(args)...));
        };
    }
    else {
        return callable;
    }
}

我想调用以下函数:

std::string& f_1(std::string& str)
{
    return str;
}

std::string& f_2(std::string& str)
{
    return str;
}

std::string& f_3(std::string& str)
{
    return str;
}

我想这样称呼它:

std::string str{ "sample text" };
concat_callable(f_1, f_2, f_3)(str);

相当于:

f_1(f_2(f_3(str)));

但目前我收到一个错误'std::string &amp;(std::string &amp;)': cannot convert argument 1 from 'std::string' to 'std::string &amp;'

由于某种原因,当我只使用两个函数时它编译得很好,例如:

concat_callable(f_1, f_2)(str);

请问有什么解决办法吗?

【问题讨论】:

    标签: c++ lambda variadic-templates c++20


    【解决方案1】:

    -&gt; decltype(auto) 作为尾随返回类型添加到 lambda。没有这个,来自返回类型的引用将被丢弃。

        return [=]
        <typename... Args>
        (Args&&... args) -> decltype(auto) {
            return callable(concat_callable(callables...)(std::forward<Args>(args)...));
        };
    

    调用concat_callablef1,f2 可以翻译:

    conact_callable(f1,f2)
        return f1(f2) 
    

    这很好用,f1 接受 string&amp;f2 返回引用。

    但有三个或更多可调用对象:

    concact_callable(f1,f2,f3)
        return f1( concat_callable(f2,f3) )
    
        /*
        here is a problem because concat_callable discards reference
        from return type and temporary string cannot be bound to
        Lvalue reference.
        */
    

    Demo

    【讨论】:

      猜你喜欢
      • 2021-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-16
      • 1970-01-01
      • 2021-06-28
      相关资源
      最近更新 更多