我有模板類。我想為其中一種類方法添加模板條件。
這個想法是對于浮點型別,我希望單獨傳遞的方法用一些 epsilon 值呼叫它。
是否可以?我想要的例子:
template<typename ValueType>
class Comparator {
public:
...
bool passed(ValueType actualValue);
template<
typename ValueType,
typename = std::enable_if_t<
std::is_floating_point<std::remove_reference_t<ValueType>>::value
>
>
bool passed(ValueType actualValue, ValueType eps) { ... }
...
};
環境:Debian 11、C 14、gcc(Debian 10.2.1-6)10.2.1 20210110
uj5u.com熱心網友回復:
是的,你可以這樣做:
#include <type_traits>
template<typename ValueType>
class Comparator {
public:
template<
typename U = ValueType,
typename = std::enable_if_t<
!std::is_floating_point<std::remove_reference_t<U>>::value
>
>
bool passed(ValueType actualValue);
template<
typename U = ValueType,
typename = std::enable_if_t<
std::is_floating_point<std::remove_reference_t<U>>::value
>
>
bool passed(ValueType actualValue, ValueType eps);
};
演示。
uj5u.com熱心網友回復:
你已經完成了大部分作業。為了多載 SFINAE,您需要使用具有指定默認值的非型別模板引數,而不是使用默認型別模板引數。
因此,我們將這兩個函式更改為使用具有默認值的非型別引數,并取消條件,例如:
template<typename ValueType>
class Comparator {
public:
...
template<
typename T = ValueType,
std::enable_if_t<
!std::is_floating_point<std::remove_reference_t<ValueType>>::value,
// ^- not here, so only non-floating point types allowed
bool> = true // set the bool to true, this lets us call the function without providing a value for it
>
bool passed(T actualValue) { non floating point code here }
template<
typename T = ValueType,
std::enable_if_t<
std::is_floating_point<std::remove_reference_t<T>>::value,
bool> = true // set the bool to true, this lets us call the function without providing a value for it
>
bool passed(T actualValue, T eps) { floating point code here }
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/329637.html
上一篇:如何裁剪影像或矩形
