[英]How can I define a templated function which takes a map and a lambda to search map-pair by value?
What I currently have is this:我目前拥有的是这样的:
std::find_if(mmap.begin(), mmap.end(),
[streamShm](const std::pair<int, StreamMapContainer> pair) {
return pair.second.pcktRefShm->id() == streamShm->id();
});
and I want to refactor this into a templated function, something like this (.cpp file):我想将其重构为模板化的 function,如下所示(.cpp 文件):
template<template <typename...> class Map, typename K, typename T, typename Lambda>
typename Map<K, T>::const_iterator findMapPairByValue(typename const Map<K, T> &map, const Lambda &lambda) {
return std::find_if(map.begin(), map.end(), lambda);
}
by this I am then able to call这样我就可以打电话了
findMapPairByValue(mmap, [streamShm](const std::pair<int, StreamMapContainer> pair) {
return pair.second.pcktRefShm->id() == streamShm->id();
});
I declared the function as extern in my header file:我在 header 文件中将 function 声明为外部:
template<template <typename...> class Map, typename K, typename T, typename Lambda>
extern typename Map<K, T>::const_iterator findMapPairByValue(typename const Map<K, T> &map, const Lambda &lambda);
But the function above doesn't compile:但是上面的 function 不能编译:
warning: 'findMapPairByValue' initialized and declared 'extern'
31 | extern typename Map<K, T>::const_iterator findMapPairByValue(typename const Map<K, T> &map, const Lambda &lambda);
| ^~~~~~~~~~~~~~~~~~
/.hpp:31:71: error: expected nested-name-specifier before 'const'
31 | extern typename Map<K, T>::const_iterator findMapPairByValue(typename const Map<K, T> &map, const Lambda &lambda);
| ^~~~~
/.hpp:31:71: error: expected '(' before 'const'
31 | extern typename Map<K, T>::const_iterator findMapPairByValue(typename const Map<K, T> &map, const Lambda &lambda);
| ^~~~~
| (
/.hpp:31:85: error: expected primary-expression before '>' token
31 | extern typename Map<K, T>::const_iterator findMapPairByValue(typename const Map<K, T> &map, const Lambda &lambda);
| ^
/.hpp:31:88: error: 'map' was not declared in this scope; did you mean 'std::map'?
31 | extern typename Map<K, T>::const_iterator findMapPairByValue(typename const Map<K, T> &map, const Lambda &lambda);
| ^~~
| std::map
Most of the body of the function is right. function的主体大部分是对的。 You just incorrectly used typename
inside parameter list:您只是在参数列表中错误地使用了typename
:
template<template <typename...> class Map, typename K, typename T, typename Lambda>
typename Map<K, T>::const_iterator findMapPairByValue(const Map<K, T> &map, const Lambda &lambda) {
return std::find_if(map.begin(), map.end(), lambda);
}
Additionally it is worth noting that template function definition should be placed in header file, not inside *.cpp file另外值得注意的是模板 function 定义应该放在 header 文件中,而不是放在 *.cpp 文件中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.