所以我一直绞尽脑汁试图想出办法。我以为我会在这里张贴,看看是否有人有任何想法。请考虑以下事项:
template <typename S, typename T, T S::* pMember>
bool SortByMember(const S& L, const S& R)
{
return L.*pMember < R.*pMember;
}
...
struct SomeStruct
{
int SomeMember;
};
void SomeFunction(void)
{
GetSortByMember<&SomeStruct::SomeMember>();
}
我希望函数GetSortByMember返回一个函数指针,指向SortByMember的相应实例。但是,我想不出以一种不要求用户也传递类类型和成员类型的方式声明/定义GetSortByMember的方法。这样:
GetSortByMember<SomeStruct, int, &SomeStruct::SomeMember>();
过于冗长,要求我说明会员类型。我确信在boost库中可能有一个解决方案,但我宁愿不将依赖项引入到我正在进行的项目中。
我非常怀疑有一个解决方案会产生我在psudocode中使用的确切语法,但也许某些事情可以用模板类或宏来完成?
SortByMember的签名是由将使用函数指针的类所期望的,因此无法更改。
答案 0 :(得分:0)
你的例子不清楚,大概是你需要用两个参数调用结果函数?如果是这样,为什么不使用getter函数并将其传递给,例如:
#include <iostream>
struct foo
{
int bar;
int getBar() const { return bar; }
};
template <typename S, typename U>
bool SortByMember(const S& L, const S& R, U f)
{
return (L.*f)()< (R.*f)();
}
int main(void)
{
foo a = {1};
foo b = {2};
std::cout << SortByMember(a, b, &foo::getBar) << std::endl;
}
答案 1 :(得分:0)
可能有更好的方法来做你想要的但是这可以使用宏和GCC特定的typeof()。我不确定但是在新的C ++标准中可能有一种可移植的方式来做类型。
#include <iostream>
template <class P, P p>
class sort_by_member_t;
template <class S, class T, T S::*p>
class sort_by_member_t<T S::*, p> {
public:
typedef bool (*fn_t)(S const&, S const&);
static bool fn(S const& L, S const& R)
{
return L.*p < R.*p;
}
};
#define SORT_BY_MEMBER(p) sort_by_member_t<typeof(p), p>::fn;
struct SomeStruct
{
int SomeMember;
};
int main()
{
bool (*fp)(SomeStruct const&, SomeStruct const&);
fp = SORT_BY_MEMBER(&SomeStruct::SomeMember);
SomeStruct const a = { 1 };
SomeStruct const b = { 2 };
std::cerr
<< (void*) fp << ' '
<< (*fp)(a, b) << ' '
<< (*fp)(b, a) << ' '
<< '\n';
return 0;
}