簡體   English   中英

如何將方法指針類型轉換為函數指針類型

[英]How to turn method pointer types into function pointer types

假設您有一個模板方法,該方法需要一個指向任何類型方法的指針。 在該模板內部,有一種方法可以將模板參數(例如方法指針類型(例如void(A::*)() ))轉換為具有相同返回類型和參數的函數指針類型,但不使用類信息( void(*)() )?

我查看了<type_traits>標頭,但沒有找到任何有幫助的內容。

C ++ 11中的一種簡單方法是使用可變參數模板進行部分專業化:

template<class PMF> struct pmf_to_pf;

template<class R, class C, class... Args>
struct pmf_to_pf<R (C::*)(Args...)>{
  using type = R(*)(Args...); // I like using aliases
};

請注意,您需要為const成員函數(理論上也需要ref限定的函數)分別進行部分專業化:

template<class R, class C, class... Args>
struct pmf_to_pf<R (C::*)(Args...) const>{
  using type = R(*)(Args...);
};

使用cv限定詞( {nil,const}{nil,volatile} )和ref限定詞( {nil, &, &&} ),您總共有2*2*3 == 12局部專業化來提供 通常,您可以省略volatile限定符,將總數降至“ just”6。由於大多數編譯器不支持function-ref-qualifiers,因此您實際上只需要2個,但是請注意其余的。


對於C ++ 03(又稱沒有可變參數模板的編譯器),可以使用以下非可變形式:

template<class PMF> struct pmf_to_pf;

template<class Sig, class C>
struct pmf_to_pf<Sig C::*>{
  typedef Sig* type; // 'Sig' is 'R(Args...)' and 'Sig*' is 'R(*)(Args...)'
};

盡管這不適用於cv限定符,但由於我認為C ++ 03不允許使用cv限定的簽名(例如R(Args...) const ),因此您可以部分擅長移除const


{...}表示某個限定詞的集合,其中nil表示空集合。 例子:

  • void f() const&將為{const}, {nil}, {&}
  • void f() &&{nil}, {nil}, {&&}

等等。

暫無
暫無

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

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