[英]How to use templated std::function as parameter?
我想為 2D-vector 制作for_each
函數,但有一個錯誤:
error: no matching function for call to ‘each(std::vector<std::vector<int> >&, main()::<lambda(int&)>)’
我該如何解決?
#include <iostream>
#include <vector>
#include <functional>
using namespace std;
template <class VarType>
void each(vector<vector<VarType>> &ve, function<void (VarType &)> action) {
for(vector<VarType> &v : ve) {
for(VarType &p : v) {
action(p);
}
}
}
int main() {
vector<vector<int>> map(5);
for(vector<int> &ve : map) {
ve.resize(4);
}
each(map, [](int &val) {
val = 1;
});
}
有幾種解決方案。 我建議只為該函數使用一個單獨的模板參數:
template <class VarType, class Function>
void each(vector<vector<VarType>> &ve, Function action) {
// no more worries
}
的問題是,編譯器不能弄清楚VarType
在function<void (VarType&)>
從傳遞拉姆達。 這樣做:
function<void(int&)> action = [](int &val) {
val = 1;
};
each(map, action);
也可以工作,因為這樣類型 ( int&
) 是已知的。
PS 在 C++17 中你可以做std::function action = [](int &val) { val = 1; };
std::function action = [](int &val) { val = 1; };
.
雖然我認為將函數作為@DeiDei 建議的另一個模板參數是更好的解決方案,但這里有一個替代方案:
如果您希望從第一個函數參數推導出VarType
,那么您可以使第二個參數成為非推導上下文:
template <class VarType>
void each(vector<vector<VarType>> &ve,
typename type_identity<function<void (VarType &)>>::type action) {
for(vector<VarType> &v : ve) {
for(VarType &p : v) {
action(p);
}
}
}
這需要 C++20 用於std::type_identity
和#include<type_traits>
,但您可以輕松實現自己的type_identity
:
template<typename T>
struct type_identity {
using type = T;
};
這是有效的,因為留給作用域解析運算符::
都是非推導的上下文,這意味着其中的模板參數不會從此函數參數推導。 您的原始函數未能通過模板參數推導,因為無法從第二個參數推導出VarType
,因為調用中給出的第二個函數參數實際上沒有類型std::function<...>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.