Created
August 29, 2011 14:33
-
-
Save Arkanosis/1178515 to your computer and use it in GitHub Desktop.
Compile-time selection of implemented methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cassert> | |
template <typename A, int (A::*)() const = &A::fun> | |
struct Checker; | |
template <typename A> | |
bool checkAndSet(int& res, const A& a, Checker<A>* = 0) | |
{ | |
res = a.fun(); | |
return false; | |
} | |
template <typename> | |
bool checkAndSet(int& , ...) | |
{ | |
return true; | |
} | |
// Return x.fun() where x is the first element of {a, b, c, d} that implements | |
// a method int fun() const. If none, return 42. | |
template <typename A, typename B, typename C, typename D> | |
int fun(const A& a, const B& b, const C& c, const D& d) | |
{ | |
int res = 42; | |
checkAndSet<A>(res, a) && checkAndSet<B>(res, b) && checkAndSet<C>(res, c) && checkAndSet<D>(res, d); | |
return res; | |
} | |
struct T | |
{ | |
int fun() const { return 12; } | |
}; | |
struct U | |
{ | |
int fun() const { return 13; } | |
}; | |
int main() | |
{ | |
T t; U u; | |
assert(fun(u, t, 2, 3) == 13); | |
assert(fun(t, t, 2, 3) == 12); | |
assert(fun('a', 2, "test", 23.23) == 42); | |
assert(fun('a', 2, t, "test") == 12); | |
} |
Bien vu, corrigé en f69f735437549563373f20fec38681c3352b7817.
Merci :-)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
C'est trop bien le SFINAE !