![](/img/trans.png)
[英]Troubles with std::enable_if and std::is_arithmetic as template parameter
[英]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.