我在类中几乎但没有完全实现函数指针,以避免重复大循环的代码。
class Scanner
{
void GenerateTextureMap();
void OtherOuterWork();
/*
Extracting the triangle sweep for loop (that is repeated code for each time we need to sweep the triangles)
Of note:
- "How can I avoid syntax errors when creating pointers to members? Use a typedef" https://isocpp.org/wiki/faq/pointers-to-members#typedef-for-ptr-to-memfn
- "How can I avoid syntax errors when calling a member function using a pointer-to-member-function? use std::invoke (C++17)" https://isocpp.org/wiki/faq/pointers-to-members#macro-for-ptr-to-memfn
*/
typedef int (Scanner::*TriangleSweepFunction)(int triangleIndex, Vec2D texv0p, Vec2D texv1p, Vec2D texv2p);
void TriangleSweep(TriangleSweepFunction p);
void MatchCameraToTrianglePaintTextureTriangle(int triangleIndex, Vec2D texv0p, Vec2D texv1p, Vec2D texv2p);
void OtherInnerWork(int triangleIndex, Vec2D texv0p, Vec2D texv1p, Vec2D texv2p);
}
void Scanner::TriangleSweep(TriangleSweepFunction p)
{
for (int triangleIndex = 0; triangleIndex < m_mesh.m_triangles.size(); triangleIndex++)
{
// ...
// loads of code
// ...
std::invoke(p, this, triangleIndex, texv0p, texv1p, texv2p);
}
}
void Scanner::MatchCameraToTrianglePaintTextureTriangle(int triangleIndex, Vec2D texv0p, Vec2D texv1p, Vec2D texv2p)
{
// Inner work on Scanner object variables
// ...
}
void Scanner::GenerateTextureMap()
{
TriangleSweep(&Scanner::MatchCameraToTrianglePaintTextureTriangle);
}
TriangleSweep(&Scanner::MatchCameraToTrianglePaintTextureTriangle);
收益
E0167 argument of type "void (Scanner::*)(int triangleIndex, Vec2D texv0p, Vec2D texv1p, Vec2D texv2p)" is incompatible with parameter of type "Scanner::TriangleSweepFunction"
Error C2664 'void Scanner::TriangleSweep(Scanner::TriangleSweepFunction)': cannot convert argument 1 from 'void (__cdecl Scanner::* )(int,Vec2D,Vec2D,Vec2D)' to 'Scanner::TriangleSweepFunction'
和
TriangleSweepFunction p = &Scanner::MatchCameraToTrianglePaintTextureTriangle;
TriangleSweep(p);
收益
E0144 a value of type "void (Scanner::*)(int triangleIndex, Vec2D texv0p, Vec2D texv1p, Vec2D texv2p)" cannot be used to initialize an entity of type "Scanner::TriangleSweepFunction"
这里的正确语法是什么?(利用已经定义的typedef)
答案 0 :(得分:1)
错别字:
typedef int (Scanner::
应该为typedef void (Scanner::
,因为我的函数返回void(void MatchCameraToTrianglePaintTextureTriangle(
void OtherInnerWork(
)
答案 1 :(得分:0)
问题在于,您创建的是函数指针,而不是指向int的指针(请注意,在类定义内无需使用Scanner :: scope运算符):
typedef int (Scanner::*TriangleSweepFunction)(int triangleIndex, Vec2D texv0p, Vec2D texv1p, Vec2D texv2p); void TriangleSweep(TriangleSweepFunction p);
您需要这样做:
typedef int * TriangleSweepFunction (int triangleIndex, Vec2D texv0p, Vec2D texv1p, Vec2D texv2p); void TriangleSweep(TriangleSweepFunction p);
//函数返回int指针
int * fun ( int, int);
//创建指向a
的函数指针
//返回int的函数类型!
int (* fun) (int , int);
注意:函数括号 创建函数指针时名称确实很重要