I’m trying to downport some C++17 code which uses if constexpr
to C++14. The code looks like this:
template<
typename T,
typename std::enable_if<std::is_integral_v<T> || std::is_floating_point_v<T> || std::is_same_v<std::decay_t<T>, std::string> ||
std::is_same_v<std::decay_t<T>, SVSTD::string_view> || std::is_same_v<std::decay_t<T>, const char*> ||
std::is_same_v<std::decay_t<T>, char*> || std::is_same_v<T, XLDateTime>>::type* = nullptr>
XLCellValue(T value) // NOLINT
{
// ===== If the argument is a bool, set the m_type attribute to Boolean.
if constexpr (std::is_integral_v<T> && std::is_same_v<T, bool>) {
m_type = XLValueType::Boolean;
m_value = value;
}
// ===== If the argument is an integral type, set the m_type attribute to Integer.
else if constexpr (std::is_integral_v<T> && !std::is_same_v<T, bool>) {
m_type = XLValueType::Integer;
m_value = int64_t(value);
}
....
I’ve done some research and found a similar question where people suggest using enable_if
to imitate what if constexpr
does. I’ve tried to do that and came up with the following translation of the code above:
template<
typename T,
typename std::enable_if<std::is_integral<T>::value && std::is_same<T, bool>::value>>
XLCellValue(T value) // NOLINT
{
// ===== If the argument is a bool, set the m_type attribute to Boolean.
m_type = XLValueType::Boolean;
m_value = value;
}
template<
typename T,
typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value>>
XLCellValue(T value) // NOLINT
{
// ===== If the argument is an integral type, set the m_type attribute to Integer.
m_type = XLValueType::Integer;
m_value = int64_t(value);
}
Unfortunately, it doesn’t compile on a C++14 gcc. The compiler shows the following error:
struct std::enable_if<std::is_integral<T>::value && std::is_same<T, bool>::value is not a valid type for a template non-type parameter
I’ve also tried to use template <class T, std::enable_if<...>>
instead of template <typename T, ...>
as described in the similar question linked above but it shows the same error.
Being a C++ noob, I’m stuck here. Can anybody help?
11