'deep'模板参数推导是否可行?
Is 'deep' template argument deduction posible?
关键是,我有模板函数,我想把它用作回调:
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;
}
为什么它不起作用?
也许如果您使用函数模板而不是函数模板?
作为
struct foo
{
template <typename ... Ind>
void operator() (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;
}
}
}
};
// ...
foo f;
matrix.modify(f, 0, 2, 3);
代码的问题
// ...........vvvvvvvvvvvvvvv template function
matrix.modify(fill_given_rows, 0, 2, 3);
函数模板不是一个对象,而是一组对象。
而且您不能将一组对象作为函数的参数传递。
您可以从集合中选择正确的对象,说明模板类型
// ...........vvvvvvvvvvvvvvvvvvvvvvvvvvvvvv now is a single object
matrix.modify(fill_given_rows<int, int, int>, 0, 2, 3);
但是(恕我直言(这有点不舒服。
传递函数(使用模板operator()
(将传递"包含"函数模板的单个对象。
相关文章:
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 是否可以对零模板参数进行模板专门化
- 函数作为模板参数,是否对返回类型强制约束
- visual是否可以在c++中创建一个接收无限数量相同类型(或至少相当数量)参数的函数
- 函数是否可以访问传递给main()的参数
- 在C++中,使用带有 std::optional 参数的函数<T>来表示可选参数是否有意义?
- 如何检查给定的参数是否为 cv::noArray()?
- 表达式 SFINAE:如何根据类型是否包含具有一个或多个参数的函数来选择模板版本
- 如果返回 -1,时间() 的参数是否被修改?
- 用于检查值是否为其任何参数的帮助程序函数
- 将类型声明为类型模板参数的模板参数的一部分是否合法?
- 模板化检查是否存在带有参数列表的类成员函数?
- 我如何知道作为参数的size_t在函数中是否有效?
- 是否可以在C++中有一个"generic"模板参数,该参数可以是非类型模板参数或类型?
- 是否可以就地构造一个固定大小的数组作为函数参数?
- C++方法是否可以根据传递给构造函数的参数具有不同的返回类型?
- 是否可以在运行时强制转换模板参数?
- 是否可以在不填充自己的参数的情况下将模板函数作为参数传递?
- 编译器是否强制根据模板参数计算表达式?
- C++中大多数/所有 setter 函数的参数是否应该写为常量引用?