Created
February 15, 2011 12:11
-
-
Save sumerman/827443 to your computer and use it in GitHub Desktop.
Static dispatch with C++ templates
This file contains 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 <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