Skip to content

Instantly share code, notes, and snippets.

@Kaminate
Last active March 31, 2016 02:36
Show Gist options
  • Save Kaminate/cf5a57538630f1eccb4d1a43a31ed27c to your computer and use it in GitHub Desktop.
Save Kaminate/cf5a57538630f1eccb4d1a43a31ed27c to your computer and use it in GitHub Desktop.
Call functions with differently ordered arguments using template specialization, c++11 variadic templates, and <utility>'s std::forward. g++ variadic_specialization.cpp -otest.exe -std=c++11
#include <utility> // std::forward
template< typename T, typename... Args >
void SetValues( T* t, Args&&... args ) {
SetValues( t );
SetValues( std::forward< Args >( args )... );
}
template<> void SetValues< int >( int *p ) { *p = 69; }
template<> void SetValues< float >( float* p ) { *p = 3.14f; }
#include <iostream> // std::cout, std::endl
int theInt;
float theFloat;
void Zero() {
theInt = 0;
theFloat = 0;
}
void Print() {
std::cout << "int: " << theInt << std::endl;
std::cout << "float: " << theFloat << std::endl;
}
int main() {
// 1. int
// 2. float
Zero();
SetValues( &theInt, &theFloat );
Print();
// 1. float
// 2. int
Zero();
SetValues( &theFloat, &theInt );
Print();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment