Skip to content

Instantly share code, notes, and snippets.

@Arkanosis
Created August 29, 2011 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Arkanosis/1178515 to your computer and use it in GitHub Desktop.
Save Arkanosis/1178515 to your computer and use it in GitHub Desktop.
Compile-time selection of implemented methods
#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);
}
@gium
Copy link

gium commented Aug 29, 2011

  • Tu peux mettre Checker* = 0x0) comme ça tu évites l'appel avec 0
  • Le if semble inutile non ?

C'est trop bien le SFINAE !

@Arkanosis
Copy link
Author

Bien vu, corrigé en f69f735437549563373f20fec38681c3352b7817.

Merci :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment