I'm trying to get a grasp of C++ metaprogramming, and how to make it a bit less painful, at least visually. I've come across this thread:
http://loungecpp.wikidot.com/tips-and-tricks:enable-if-for-c-11
Suggesting a more pleasent-to-read version of std::enable_if
. Here's the code:
template <typename T>
using Invoke = typename T::type;
template <typename Condition>
using EnableIf = Invoke<std::enable_if<Condition::value>>;
// Left as an exercise to the reader on the original page - I hope I got it right
template <typename Condition>
using DisableIf = Invoke<std::enable_if<!Condition::value>>;
When I try to use them, however, it seems that the non-integral version behaves just like the integral one, i.e. the DisableIf behaves like an EnableIf. Code:
template <typename T, typename = EnableIf<std::is_integral<T>> >
void foo(const T& t) { std::cout << t << " is integral!"; }
template <typename T, typename = DisableIf<std::is_integral<T>> >
void foo(const T& t) { std::cout << t << " is_ not_ integral!"; }
int main() {
foo(123); foo(456.0);
}
Compiler output (g++ 5.1.1 --std=c++14
):
g.cpp:21:6: error: redefinition of ‘template<class T, class> void foo(const T&)’
void foo(const T& t) { std::cout << t << " is_ not_ integral!"; }
^
g.cpp:18:6: note: ‘template<class T, class> void foo(const T&)’ previously declared here
void foo(const T& t) { std::cout << t << " is integral!"; }
^
g.cpp: In function ‘int main()’:
g.cpp:24:24: error: no matching function for call to ‘foo(double)’
foo(123); foo(456.0);
^
g.cpp:18:6: note: candidate: template<class T, class> void foo(const T&)
void foo(const T& t) { std::cout << t << " is integral!"; }
^
g.cpp:18:6: note: template argument deduction/substitution failed:
Is it an error with my DisableIf
definition, or is something else the matter?