【发布时间】:2019-04-21 15:33:01
【问题描述】:
说明:
CLion 和它的标准编译器给我一个错误,即“候选模板 [被] 忽略”,当我为一个以 lambda 作为参数的通用函数编写一个 lambda 作为参数时。
此 lambda 采用泛型类型 T 并返回另一个未知类型 A。
我正在编写的容器类应该支持像 Scala 中的这些函数操作或来自 Java Stream API 的函数操作。
确切地说:
地图功能带来了巨大的问题。它被实现为一个名为 Sequence 的类中的成员函数,该类接受一个泛型参数T。
它应该采用已知类型T 的元素(实际上它遍历整个序列)并将其转换为未知类型A。
实现本身不是问题,但我无法使用我知道的 lambda 语法调用该函数。
代码:
Sequence.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)>'
} );
提前致谢!
【问题讨论】:
-
您需要将
a.map(替换为a.map<uint32_t>(,因为这里无法推断出类型。 IMO 的正确解决方案是不要在这里使用std::function。请改用转发参考 (template <typename F> auto map(F && func).
标签: c++ templates lambda c++17 template-argument-deduction