将非模板函数指针传递到模板方法中
Passing a non-template function pointer into a template method
我搜索了谷歌和stackoverflow,但找不到解决这种情况的东西:
- 我有一个带有方法的模板,该方法使用函数指针
- 函数指针本身不是一个模板,它是一个普通的函数指针
- 然而,函数指针的参数中使用了模板参数
文件名:otherclasses.h
// This class is used as the template parameter class B { public: B() {} ~B() {} int getVal() const { return val; } void setVal(int v) { val = v; } private: int val; }; // This is just a static function class A { public: static bool someStaticFunction(const B* left, const B* right); }; inline bool A::someStaticFunction( const B* left, const B* right) { return left->getVal() < right->getVal(); }
文件名:templateheader.h
#include "otherclasses.h" template<typename T> class theTemplate { public: void insert(T val1, T val2) { stuff[0] = val1; stuff[1] = val2; } bool usesSomeStaticFunction(bool (*funcp)(const T, const T)) { // will return true return funcp(stuff[0],stuff[1]); } private: T stuff[2]; };
文件名:main.cpp
#include "otherclasses.h" #include "templateheader.h" #include <stdio.h> int main() { theTemplate<B*> foo; printf("%dn", foo.usesSomeStaticFunction(A::someStaticFunction)); return 0; }
Visual Studio的错误:
error C2664: 'theTemplate<T>::usesSomeStaticFunction' : cannot convert parameter 1 from 'bool (__cdecl *)(const B *,const B *)' to 'bool (__cdecl *)(const T,const T)' with [ T=B * ] None of the functions with this name in scope match the target type
解决这个问题的两种方法:
- 使用
const void*
而不是const T*
- 从函数指针的参数和任何使用它的参数中删除
const
感谢您的帮助
更新
事实证明,有一个更好的解决方案-只需在静态函数中将const
移到B*
的右边
文件名:otherclasses.h已编辑
// This class is used as the template parameter // This is unchanged. class B { public: B() {} ~B() {} int getVal() const { return val; } void setVal(int v) { val = v; } private: int val; }; // This is just a static function // This is changed class A { public: // The "const" is moved to the right side of B* static bool someStaticFunction(B* const left, B* const right); }; // This is changed inline bool A::someStaticFunction( // The function definition must match the function prototype... B* const left, B* const right) { return left->getVal() < right->getVal(); }
const T
变成了T* const
,而不是T const*
。一种解决方案是重新编写代码,使其不包含T
(T
=B
)中的指针,而是包含在模板类中:
template<typename T>
class theTemplate
{
public:
void insert(T* val1, T* val2)
{
stuff[0] = val1;
stuff[1] = val2;
}
bool usesSomeStaticFunction(bool (*funcp)(const T*, const T*))
{
// will return true
return funcp(stuff[0],stuff[1]);
}
private:
T* stuff[2];
};
相关文章:
- 模板函数指针和lambda
- 将成员函数指针作为参数传递给模板方法
- 模板方法访问正向声明的类仅在没有此指针的情况下无法编译
- C++11:模板方法的模板函数调用无法编译?
- 如何从ECS中的模板方法获取组件?
- 使用 SFINAE 设计模板方法
- 一个模板方法,用于同时接受常量和非常量参数
- 具有推导参数的模板函数指针数组变量
- 将一个类的方法指针存储到另一个类中
- C++模板方法中的循环依赖关系
- 在 C++ 中使用模板方法重写类方法
- 派生的成员 通过指向基、static_cast、crtp、删除模板的指针
- 指向类模板方法的 void 指针的向量
- 使用模板、方法指针和字符串键入推导
- 模板化方法指针 - 无法匹配函数参数的指针
- 获取特定的模板重载方法指针
- 将非模板函数指针传递到模板方法中
- c++模板方法专门化以返回指针或引用
- 通过指向模板方法的指针调用模板方法
- clang vs gcc和msvc中的方法指针模板