簡體   English   中英

我想要一個帶有指向成員的指針的模板函數,但是我不想傳遞類類型或成員類型

[英]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庫中可能有一個解決方案,但我不想將這種依賴關系引入到我正在從事的項目中。

我高度懷疑是否有一種解決方案能夠產生我在psudocode中使用的確切語法,但是也許可以通過模板類或宏來完成某些工作?

使用函數指針的類需要使用SortByMember的簽名,因此無法更改。

您的示例不清楚,想必您需要使用兩個參數來調用結果函數嗎? 如果是這樣,為什么不使用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;
}

可能有更好的方法來執行所需的操作,但這可以使用宏和特定於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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM