Created
August 31, 2017 06:58
-
-
Save Matthewacon/451f99f155e22ab12713e195e82825b8 to your computer and use it in GitHub Desktop.
Did you just misappropriate the arguments to my clusterf*ck of unreadable specialized template functions?
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 <iostream> | |
//Intermediary Dummy Type | |
class ITest; | |
//Base class | |
template<typename T=ITest> | |
class Test { | |
public: | |
Test() { | |
//Ensure that subclasses implement these methods, if not then throws compiler error | |
void (T::*func)(int) = &T::param, (T::*func2)() = &T::noParam; | |
} | |
void param(int i); | |
void noParam(); | |
}; | |
//Subclass of Test, implements methods | |
class SubTest : Test<SubTest> { | |
public: | |
void param(int i) { | |
std::cout << i << std::endl; | |
} | |
void noParam() { | |
std::cout << "Hello, World!" << std::endl; | |
} | |
}; | |
//Function consumer that invokes the passed function with the argument '0' | |
void functionConsumer(void (*consumeMe)(int)) { | |
(*consumeMe)(0); | |
return; | |
} | |
//Dummy function with the same signature as the argument for 'functionConsumer' | |
void aPlusB(int i) { return; } | |
int main() { | |
SubTest* test = new SubTest(); | |
//'func' is a pointer to a member function of 'SubTest' | |
void (SubTest::*func)(int) = &SubTest::param; | |
/* De-pointerize 'test' and invoke the (de-pointerized) member function pointer on 'test' with the | |
* argument '0'. OK, PRINTS "0" | |
*/ | |
(test->*func)(0); | |
//Illegal operation, you cannot cast a member function pointer to a normal function pointer. NOT OK! | |
// void (*func2)(int) = ((*)(int))func; | |
//Passes a reference to 'aPlusB' to 'functionConsumer'. '&aPlusB' is of the type '(*)(int)'. OK, DOES NOTHING | |
functionConsumer(&aPlusB); | |
/* Illegal operation, you cannot pass a member function pointer into 'functionConsumer'. | |
* 'func' is of the type '(SubClass::*)(int)' and NOT '(*)(int)'. NOT OK! | |
*/ | |
// functionConsumer(func); | |
int i = ({8;}); | |
//Some spicy C syntax that unfortunately doesn't work in C++ :thonked: (statement expressions are amazing) | |
// functionConsumer(({ | |
// void function(int arg) { | |
// std::cout << arg << std::endl; | |
// } (void (*)(int))function; | |
// })); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment