我想要一个接受指向成员的指针的模板函数,但我不想传递类类型或成员类型

I want a template function that takes a pointer to member, but I don't want to have to pass the class type nor the member type

本文关键字:成员 类型 函数 我不想 成员类 指针 一个 我想要      更新时间:2023-10-16

所以我一直在绞尽脑汁想办法解决问题。我想把它贴在这里,看看有没有人有什么想法。考虑以下内容:

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库中可能有一个解决方案,但我宁愿不把这种依赖引入到我正在工作的项目中。

我非常怀疑是否有一种解决方案可以产生我在伪代码中使用的确切语法,但也许可以用模板类或宏做些什么?

SortByMember的签名是使用函数指针的类所期望的,所以它不能被改变。

可能有更好的方法来做您想做的事情,但这可以使用宏和GCC特定的typeof()。我不确定,但是在新的c++标准中可能会有一种可移植的方法来实现typeof。

#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;
}

您的示例不清楚,想必您需要使用两个参数调用结果函数?如果是这样,为什么不使用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;
}