Overloading — enable_if (2)
// Copyright 2014 Andrzej Krzemienski.
//
// This shows how to use enable_if for controlling
// which function overload to pick based on the compile-time
// properties of the argument type.
//
// REQUIRES C++11
#include <cassert>
#include <type_traits>
#define ENABLE_IF(...) \
typename std::enable_if<__VA_ARGS__::value>::type* = nullptr
template <typename T>
struct optional
{
// optional always uninitialized
explicit operator bool() const { return false; }
T value() const { throw int(); }
template <typename U, ENABLE_IF(std::is_convertible<U, T>)>
T value_or(U const& v) const
{
if (*this)
return this->value();
else
return v;
}
template <typename F, ENABLE_IF(!std::is_convertible<F, T>)>
T value_or(F const& f) const
{
if (*this)
return this->value();
else
return f();
}
};
int def()
{
return -1;
}
int main()
{
optional<int> oi;
assert (oi.value_or(1) == 1);
assert (oi.value_or(&def) == -1);
}
Like this:
Like Loading...
ENABLE_IF must be in fuction arguments not in template arguments.
In C++11, SFINAE also works for template parameters. This code compiles and behaves as expected with C++11 compilers.
Didn’t know that, thanks.