簡體   English   中英

如何強制編譯器選擇特定的函數專業化

[英]How to force a compiler to choose a specific function specialization

例如,我有兩個類:

class Foo {
public:
    const bool operator==(const Foo&) const;

    template<class _Ty>
    const bool operator==(const _Ty&) const;
};

class Bar : public Foo { };

像這樣的代碼:

Foo& foo;
Bar& bar;

const bool equality = (foo == bar);

顯然,編譯器將選擇模板函數來評估此表達式,因為需要將變量bar轉換為Foo&才能調用專門的operator== 但是,當參數是從Foo派生的類的實例(例如,添加/刪除某些修飾符或其他內容)時,有什么方法可以強制編譯器(無需將Bar&轉換為Foo& )首先選擇特殊化,而不是模板函數? )?

當參數是從Foo派生的類的實例時,有什么方法可以強制編譯器(無需將Bar&轉換為Foo&)首先選擇特殊化,而不是模板函數?

是的,您可以使用traits類型 具體來說,您可以按以下方式使用std::enable_ifstd::is_base_of

template<typename Type>
typename std::enable_if<
    std::is_base_of<Foo, Type>::value,
    const bool
>::type
operator==(const Type&) const { … }

template<typename Type>
typename std::enable_if<
    !std::is_base_of<Foo, Type>::value,
    const bool
>::type
operator==(const Type&) const { … }

現場演示

您基本上可以基於模板參數激活/禁用重載。

您也可以通過添加一個別名使事情變得稍微更具可讀性:

template<class Type>
using is_fooable = std::is_base_of<Foo, Type>;

現場演示

暫無
暫無

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

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