我想要一个接受指向成员的指针的模板函数,但我不想传递类类型或成员类型
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
所以我一直在绞尽脑汁想办法解决问题。我想把它贴在这里,看看有没有人有什么想法。考虑以下内容:
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;
}
相关文章:
- 根据模板类型选择类模板的成员类型?
- 函数模板签名中忽略的成员类型def 的访问说明符
- 在C++如何从数组中提取成员并返回成员类型的数组?
- C++从成员类型中扣除类型的功能模板?
- 无法初始化以 std::byte 作为成员类型的位字段
- 构造函数可以更改默认成员类型吗?
- 使用相同方法但不同成员类型构建类的最佳方法
- 允许通过指向方法的成员参数的指针来推断模板参数所指向的成员类型
- 使用 std::条件根据模板参数选择成员类型
- CRTP:如何推断要用作返回类型的成员类型?
- 对成员类型的成员方法使用 std::result_of<>
- C :可以从类及其受保护的成员类型继承可以继承吗?
- 如何在不指定不必要的模板参数的情况下使用模板类的成员类型
- 基类数据成员类型取决于派生类
- C 多态性:允许模棱两可的成员类型
- 使用使用成员类型别名的构造函数来推论类模板参数
- 获取与在模板参数中传递的函数成员类型相同的类
- 如果静态成员未初始化并且成员类型是类本身,该怎么办?
- boost::bind 无法绑定到纯虚拟基类中定义的非静态函数模板成员类型
- 将联合强制转换为其成员类型之一