<分区>
解释:
CLion 及其标准编译器给我一个错误,即“候选模板 [被] 忽略”,当我将 lambda 编写为以 lambda 作为参数的通用函数的参数时。
此 lambda 采用通用类型 T
并返回另一个未知类型 A
。
我正在编写的容器类应该支持像 Scala 中的这些功能操作或来自 Java Stream API 的功能操作。
准确地说:
map 功能会带来很大的问题。它作为一个名为 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)>'
} );
提前致谢!