簡體   English   中英

C ++函數指針

[英]C++ function pointer

在C ++中,有沒有一種方法可以制作“未使用”的函數指針? 例如:

// pointer to global function
void foo( void (*fptr)() );

// pointer to member
void foo( void (Bar::*fptr)() );

有沒有辦法可以刪除該成員所在的類? 這樣我可以做這樣的事情:

void foo( void ("any type"::*fptr)(), "same type as for the pointer" &instance );

然后,在foo中,我想將該指針存儲在列表中,這樣我就可以遍歷列表並調用所指向的函數/成員,而不管它屬於哪個類。 當然,我需要在其上調用該函數的實例列表。

謝謝。

您可以使用模板。

template<typename T> void foo( void(T::*)(), T&) { ... }

但是,人們更喜歡使用功能對象方法。 您可以動態或靜態地執行此操作。

void foo(std::function<void()> func) {
    // std::bind is used to make this out of a member function
}
template<typename T> void foo(T t = T()) {
    t(); // This is the best approach.
}

編輯:一些例子。

void foo(std::function<void()> func) {
    std::cout << "In example one ";
    func();
}
template<typename T> void foo(T t = T()) {
    std::cout << "In example two ";
    t();
}
class some_class {
public:
    void func() { std::cout << "in ur function!\n"; }
};
int main(void)
{
    some_class* ptr = NULL;
    struct tempfunctor {
        tempfunctor(some_class* newptr)
            : ptr(newptr) {}
        some_class* ptr;
        void operator()() { return ptr->func(); }
    };
    foo(tempfunctor(ptr)); // Calls example two
    foo(std::function<void()>(tempfunctor(ptr))); // Calls example one
    foo(std::function<void()>(std::bind(&some_class::func, ptr)); // I'm not that familiar with bind, it looks something similar to this.
    std::cin.get();
}

這是一種稱為函數對象慣用語的慣用語,在STL和其他高質量庫中大量使用。 編譯時模板比較干凈,但是std :: function可以在運行時綁定。

編輯@ OP:我在那里沒有看到您的列表要求。 std::function<void()>是您的最佳選擇。

以下似乎可以在g ++和MSVC上正常工作:

#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <iostream>
using namespace std;

void foo( boost::function<int()> f )
{
    cout << "f() = " << f() << endl;
}

template< class Type >
void foo( int (Type::*f)() const, Type const& o )
{
    foo( boost::bind( f, boost::ref( o ) ) );
}

int func1() { return 1; }
struct S { int func2() const { return 2; } };

int main()
{
    foo( func1 );
    foo( &S::func2, S() );
}

免責聲明:我很少使用Boost的東西,我只是打了上面的代碼而不必費心檢查文檔,因此可以更清晰地表達它。

還要注意,C ++ 0x標准庫提供了相同的功能。

干杯,……

否。綁定類是成員函數指針類型的固有部分。

但是,您可以使用指向通用基類或模板的成員函數指針。

您可以在列表中使用函子嗎?

http://en.wikipedia.org/wiki/Function_object

看看快速代表: http : //www.codeproject.com/KB/cpp/FastDelegate.aspx

這是一個簡單的嵌入式庫,可讓您以很高的速度委派幾乎所有內容。

您不能有這樣的指針,但是您可以具有boost::any的集合,並將異構指針(或任何類型的仿函數 )放入其中。

template <typename T>
void foo( void (T::*fptr)(), T& instance)
{
    // ...
}

我不會在這里扮演專家,但是我認為這會奏效,否則我想知道為什么。

您不能這樣做,即使可以也不要這樣做,因為這違反了語言的精神。 創建一個以“ fptr”作為純虛擬成員的基類,並從該類繼承所有類。

暫無
暫無

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

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