将函数传递给模板时使用函数指针或对象有什么区别
What is the difference between using function pointers or an object when passing a function to a template?
假设我想从<algorithm>
实现std::find_if
。这是我尝试的一种可能的方法。
template <class In, class F>
In find_if(In b, In e, F f)
{
while (b != e)
{
if (f(*b))
return b;
b++;
}
return e;
}
在这里,用户似乎需要知道传递一个返回bool
值的参数。我的部分问题涉及是否有任何方法可以限制使用此技术传递给F f
的内容。
实现这一点的另一种方法是使用函数指针:
template <bool (*F)(int), class In>
In find_if(In b, In e)
{
while (b != e)
{
if (F(*b))
return b;
b++;
}
return e;
}
这两种方法之间有什么区别吗(除了必须调用它们的方式;即第一种方式用find_if(arg1,arg2,f)
调用,第二种方式用find_if<f>(arg1,arg2)
调用。
如果有分歧,你能给我描述和解释一下吗?
传递
函数指针比传递我们对其应用(*b)
的类型更具限制性。
在课程的情况下,您可以通过
函子类(可能具有状态)为:
struct HasName { explicit HasName(const std::string& name) : name(name) {} template <typename T> bool operator () (const T& t) const { return t.get_name() == name; } std::string name; };
或任何函数指针,其中
f(*b)
是正确的(例如,f
可以采用浮点数,而*b
是int
)。- 或 lambda (C++11)。
相关文章:
- QMetaObject invokeMethod的基于函数指针的语法
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- c++r值引用应用于函数指针
- 模板函数指针和lambda
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 带有类的函数指针
- () 函子后面的括号,而不是函数指针?
- 全局作用域中函数指针的赋值
- 使用"Task"函数指针队列定义作业管理器
- 将成员函数指针作为参数传递给模板方法
- 如何创建对象函数指针C++映射?
- 匹配函数指针作为模板参数?
- 通过函数指针定义类范围之外的方法
- 存储在类中的函数指针
- C++从函数指针数组调用函数
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 整数键映射到头文件中的成员函数指针
- 从类成员函数到类 C 函数指针的转换
- 如何将内联匿名函数分配给C++函数指针
- 将字符缓冲区强制转换为函数指针