簡體   English   中英

解析 const 和 non-const 成員 function 指針

[英]Resolve const and non-const member function pointer

在下面的代碼片段中,我希望能夠從doWork調用A::foo

但是,由於foo有兩個重載( const和非const ),編譯器無法解析我在調用doWork時指的是哪一個。 有沒有辦法告訴編譯器我的意思是哪個。

我無法更改struct A

我可以在 doWork 的簽名或 doWork 的調用中做一些事情來總是選擇說 const 嗎?

我知道的一種解決方案是將 function 指針類型作為doWork的參數而不是模板(像這樣) void doWork(void (A::*fun)(void) const){但這有點難看,我希望找到一個基於模板的解決方案(如果存在)

struct A{
    void foo() const {
    }
    void foo(){
    }
    void bar(){
    }
    void bar() const {
    }
};

template<typename F>
void doWork(F fun){
    const A a;
    (a.*fun)();
}

int main()
{
    doWork(&A::foo); //error: no matching function for call to ‘doWork()’
    doWork(&A::bar); // error: no matching function for call to ‘doWork()’
    return 0;
}

您可以使用static_cast來指定應該使用哪一個。

static_cast也可用於通過執行到特定類型的函數到指針轉換來消除 function 重載的歧義,如

std::for_each(files.begin(), files.end(), static_cast<std::ostream&(*)(std::ostream&)>(std::flush));

例如

doWork(static_cast<void (A::*)(void) const>(&A::foo));
doWork(static_cast<void (A::*)(void) const>(&A::bar));

或者明確指定模板參數。

doWork<void (A::*)(void) const>(&A::foo);
doWork<void (A::*)(void) const>(&A::bar);

您可以使用:

template <typename T>
void doWork(void (T::*fun)() const){
    const A a;
    (a.*fun)();
}

更通用的 function 模板將使用const T a

template <typename T>
void doWork(void (T::*fun)() const){
    const T a;
    (a.*fun)();
}

請注意,第二個版本在任何地方都沒有假定A

暫無
暫無

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

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