如何为通用 lambda 参数定义模板参数? [复制]

2023-12-19

解释:

当我编写 lambda 作为以 lambda 作为参数的泛型函数的参数时,CLion 及其标准编译器给我一个错误,即“候选模板被忽略”。 该 lambda 采用泛型类型T并返回另一个未知类型A.

我正在编写的容器类应该支持 Scala 中的功能操作或 Java Stream API 中的功能操作。

确切地说: 地图功能会带来很大的问题。它是作为名为 Sequence 的类中的成员函数实现的,该类采用通用参数T。 它应该采用已知类型的元素T(实际上它遍历整个序列)并将其转换为未知类型A。 实现本身不是问题,但我无法使用我知道的 lambda 语法调用该函数。

Code:

序列.h

template< typename T >
class Sequence {
public:
    template< typename A >
    auto map( std::function< A( const T ) > function ) const {
        auto sequence = new Sequence< A >;
        for ( const T& element : *this ) {
            sequence->push( function( element ) );
        }
        return *sequence;
    }
}

main.cpp

int main() {
    Sequence< uint32_t > a;
    a.push( 20 );
    a.push( 30 );
    a.push( 40 );

    a.map( []( uint32_t c ) -> uint32_t {
        return c * c;
    } );
    return 0;
}

据我了解 lambda 被初始化, 接受一个类型的参数std::uint32_t并返回一个类型的值std::uint32_t。 通用参数A目前似乎还没有推断出来。

错误堆栈:

main.cpp:21:7: error: no matching function for call to 'Sequence<unsigned int>::map(main()::<lambda(uint32_t)>)'
     } );

Sequence.h:143:10: note: candidate: template<class A> auto Sequence<T>::map(std::function<A(T)>) const [with A = A; T = unsigned int]
     auto map( std::function< A( const T ) > function ) const {

note:   template argument deduction/substitution failed:
main.cpp:21:7: note:   'main()::<lambda(uint32_t)>' is not derived from 'std::function<A(unsigned int)>'
     } );

提前致谢!


忽略const问题,你有一个先有鸡还是先有蛋的问题。

确实,您的 lambda 可以转换为std::function<std::uint32_t(std::unit32_t)>.

但 lambda 确实不是std::function<std::uint32_t(std::unit32_t)>所以编译器无法推断A.

如果编译器无法推断出A,无法将 lambda 转换为std::function<A(T)>.

你显然可以明确正确的std::function类型调用map()

a.map(std::function<std::uint32_t(std::uint32_t)>{[]( uint32_t c ) -> uint32_t {
    return c * c;
}});

并且,考虑到您正在使用 C++17(因此您可以使用推导指南std::function)还推导出模板参数std::function

a.map(std::function{[]( uint32_t c ) -> uint32_t {
    return c * c;
}});

但是,再次使用模板推导指南std::function, 写作怎么样mat()接受一个简单的可调用和推论A从中?

我的意思是...下面的事情怎么样?

template <typename F>
auto map( F && func ) const {
    using A = typename decltype(std::function{std::forward<F>(func)})::result_type;

    auto sequence = new Sequence< A >;
    for ( const T& element : *this ) {
        sequence->push( std::forward<F>(func)( element ) );
    }
    return *sequence;
}

(警告:代码未经测试)。

你还可以推论A, 没有std::function演绎指南(C++17 之前的版本),由 Michael Kenzel 建议。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何为通用 lambda 参数定义模板参数? [复制] 的相关文章

随机推荐