如何Contains在類模板中多載函式模板Range?
當我運行此代碼時,我收到如下錯誤:
template <typename T>
class Range {
public:
Range(T lo, T hi) : low(lo), high(hi)
{}
typename std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type
Contains(T value, bool leftBoundary = true, bool rightBoundary = true) const
{
// do sth
return true;
}
typename std::enable_if<std::numeric_limits<T>::is_integer, bool>::type
Contains(T value, bool leftBoundary = true, bool rightBoundary = true) const
{
// do sth
return true;
}
};
error: ‘typename std::enable_if<std::numeric_limits<_Tp>::is_integer, bool>::type Range<T>::Contains(T, bool, bool) const’ cannot be overloaded
Contains(T value, bool leftBoundary = true, bool rightBoundary = true) const
^~~~~~~~
error: with ‘typename std::enable_if<(! std::numeric_limits<_Tp>::is_integer), bool>::type Range<T>::Contains(T, bool, bool) const’
Contains(T value, bool leftBoundary = true, bool rightBoundary = true) const
uj5u.com熱心網友回復:
你也需要Contains自己制作模板。例如
template <typename X>
typename std::enable_if<!std::numeric_limits<X>::is_integer, bool>::type
Contains(X value, bool leftBoundary = true, bool rightBoundary = true) const
{
// do sth
return true;
}
template <typename X>
typename std::enable_if<std::numeric_limits<X>::is_integer, bool>::type
Contains(X value, bool leftBoundary = true, bool rightBoundary = true) const
{
// do sth
return true;
}
從 C 17 開始,您可以使用Consexpr If而不是多載。
bool
Contains(T value, bool leftBoundary = true, bool rightBoundary = true) const
{
if constexpr (!std::numeric_limits<T>::is_integer) {
// do sth
return true;
} else {
// do sth
return true;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/447273.html
上一篇:在函式模板的回傳型別中使用decltype可消除由于例外規范引起的錯誤
下一篇:模板模板引數推導與C 類模板
