Skip to content

Instantly share code, notes, and snippets.

@sumerman
Created February 15, 2011 12:11
Show Gist options
  • Save sumerman/827443 to your computer and use it in GitHub Desktop.
Save sumerman/827443 to your computer and use it in GitHub Desktop.
Static dispatch with C++ templates
#include <cstdlib>
#include <iostream>
using namespace std;
struct Functor {
inline int operator () (int i, char c) {
return i+c;
}
};
struct SpecFunctor {
inline char operator () () {
return 'a';
}
};
template <int N>
struct Sel {
enum {
sel = N
};
};
namespace OuterName {
template <typename S>
struct Inner {
typedef Functor method;
};
template <>
struct Inner< Sel<1> > {
typedef SpecFunctor method;
};
struct Outer {
template <typename T>
inline typename Inner<T>::method operator [] (T) {
typename Inner<T>::method f;
return f;
}
};
}
#define ID(n) [Sel<n>()]
int main() {
OuterName::Outer obj;
//cout << obj ID(0)(2,3) << endl;
char c = obj ID(1)();
//cout << obj ID(1)() << endl;
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment