簡體   English   中英

針對類的enable_if和is_arithmetic模板專業化

[英]Template specialisation with enable_if and is_arithmetic for a class

我正在嘗試實現2類專門用於算術類型的Expression類。 這是默認類:

template<typename Left, typename Op, typename Right, typename std::enable_if<!std::is_arithmetic<Left>::value, Left>::type* = nullptr>
class Expression { /* ... */ }

這是兩個專業:

template<typename Left, typename Op, typename Right, typename std::enable_if<std::is_arithmetic<Left>::value, Left>::type* = nullptr>
class Expression { /* ... */ };

template<typename Left, typename Op, typename Right, typename std::enable_if<std::is_arithmetic<Right>::value, Right>::type* = nullptr>
class Expression { /* ... */ };

如果現在編譯我的代碼,則會出現此錯誤:

錯誤C3855'表達式':模板參數'__formal'與聲明Vector不兼容

在使用模板時,如何解決模板,專業化或虛擬類型的問題。

您有多個主類模板,這些模板無法替換。 您需要一個主模板,然后是多個專業化模板。 一種簡單的方法是采用不同的方法:

template<typename Left, typename Op, typename Right,
         int = std::is_arithmetic_v<Left> + 2 * std::is_arithmetic_v<Right>>
class Expression;

template <typename Left, typename Op, typename Right>
class Expression<Left, Op, Right, 0> {
    // base case
};
template <typename Left, typename Op, typename Right>
class Expression<Left, Op, Right, 1> {
    // only the left operand is arithmetic
};
template <typename Left, typename Op, typename Right>
class Expression<Left, Op, Right, 2> {
    // only the right operand is arithmetic
};
template <typename Left, typename Op, typename Right>
class Expression<Left, Op, Right, 3> {
    // both operands are arithmetic
};

如果您有多個可以一起處理的案例,則可以制作這些主要模板,並僅對其余的特殊案例進行專業化處理。

暫無
暫無

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

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