[Assorted-commits] SF.net SVN: assorted:[1197] sandbox/trunk/src/cc/tmpl_fn_ptrs.cc
Brought to you by:
yangzhang
From: <yan...@us...> - 2009-02-18 18:32:02
|
Revision: 1197 http://assorted.svn.sourceforge.net/assorted/?rev=1197&view=rev Author: yangzhang Date: 2009-02-18 18:31:55 +0000 (Wed, 18 Feb 2009) Log Message: ----------- added question submitted to stackoverflow Added Paths: ----------- sandbox/trunk/src/cc/tmpl_fn_ptrs.cc Added: sandbox/trunk/src/cc/tmpl_fn_ptrs.cc =================================================================== --- sandbox/trunk/src/cc/tmpl_fn_ptrs.cc (rev 0) +++ sandbox/trunk/src/cc/tmpl_fn_ptrs.cc 2009-02-18 18:31:55 UTC (rev 1197) @@ -0,0 +1,46 @@ + // How do I do set templated function pointers? + // + // See <http://stackoverflow.com/questions/560322/how-else-to-achieve-templated-function-pointers>. + + #include <iostream> + using namespace std; + + template<typename T> void write0(T msg) { cout << "write0: " << msg.name() << endl; } + template<typename T> void write1(T msg) { cout << "write1: " << msg.name() << endl; } + + // This isn't so bad, since it's just a conditional (which the processor will + // likely predict correctly most of the time). + bool use_write0; + template<typename T> void write(T msg) { if (use_write0) write0(msg); else write1(msg); } + + struct MsgA { const char *name() { return "MsgA"; } }; + struct MsgB { const char *name() { return "MsgB"; } }; + struct MsgC { const char *name() { return "MsgC"; } }; + struct MsgD { const char *name() { return "MsgD"; } }; + + // This doesn't work: templates may not be virtual. + #if 0 + struct Writer { template<typename T> virtual void write(T msg) = 0; }; + struct Writer0 { template<typename T> virtual void write(T msg) { cout << "write0: " << msg.name() << endl; } }; + struct Writer1 { template<typename T> virtual void write(T msg) { cout << "write0: " << msg.name() << endl; } }; + #endif + + int main(int argc, char **argv) { + use_write0 = argc == 1; + + // I can do this: + write(MsgA()); + + // Can I achieve the following without the verbosity (manual setup, named + // template instantiations, etc.)? + void (*pwriteA)(MsgA) = use_write0 ? (void(*)(MsgA)) write0<MsgA> : (void(*)(MsgA)) write1<MsgA>; + void (*pwriteB)(MsgB) = use_write0 ? (void(*)(MsgB)) write0<MsgB> : (void(*)(MsgB)) write1<MsgB>; + void (*pwriteC)(MsgC) = use_write0 ? (void(*)(MsgC)) write0<MsgC> : (void(*)(MsgC)) write1<MsgC>; + void (*pwriteD)(MsgD) = use_write0 ? (void(*)(MsgD)) write0<MsgD> : (void(*)(MsgD)) write1<MsgD>; + pwriteA(MsgA()); + pwriteB(MsgB()); + pwriteC(MsgC()); + pwriteD(MsgD()); + + return 0; + } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |