【发布时间】:2019-10-19 22:53:18
【问题描述】:
关键是,我有模板函数,我想用它作为回调:
template <class ...Ind>
void fill_given_rows(mat& matrix, Ind ...ind){
它从这样的类成员函数中调用:
template<typename F, class ... Args>
void pic::modify(F func, Args ... args){
func(matrix, args...);
}
哪一个按顺序从 main 调用为:
matrix.modify(fill_given_rows, 0, 2, 3);
gcc 给了我这样的输出:
50:41: error: no matching function for call to 'pic::modify(<unresolved overloaded function type>, int, int, int)'
50:41: note: candidate is:
27:8: note: template<class F, class ... Args> void pic::modify(F, Args ...)
27:8: note: template argument deduction/substitution failed:
50:41: note: couldn't deduce template parameter 'F'
这里是完整版代码:
#include <vector>
#include <array>
#include <initializer_list>
#include <type_traits>
typedef std::vector<std::vector<int>> mat;
template <class ...Ind>
void fill_given_rows(mat& matrix, Ind ...ind){
std::array<std::common_type_t<Ind...>, sizeof...(Ind)> lines = {{ind...}};
int height = matrix.size();
int width = matrix[0].size();
for(auto row: lines){
for(int y=0; y<width; y++){
matrix[row][y]=1;
}
}
}
class pic{
public:
pic(int width, int height); //generate empty matrix
//callback for all matrix modification
template<typename F, class ... Args>
void modify(F, Args ...);
private:
mat matrix;
};
pic::pic(int width, int height){
matrix.resize(height);
for(auto& row: matrix){
row.resize(width);
}
}
template<typename F, class ... Args>
void pic::modify(F func, Args ... args){
func(matrix, args...);
}
int main() {
int width=10, height=5;
pic matrix(width, height);
matrix.modify(fill_given_rows, 0, 2, 3);
return 0;
}
为什么它不起作用?
【问题讨论】:
-
请提供minimal reproducible example。关于 stackoverflow 的问题必须是自包含的。链接将来可能会中断,然后这个问题就毫无价值了。
-
无法推断出
F的类型。你需要matrix.modify(fill_given_rows<int, int, int>, 0, 2, 3);
标签: c++ templates variadic-templates template-argument-deduction