Skip to content

Instantly share code, notes, and snippets.

@hratcliffe
Last active October 25, 2024 13:09
Show Gist options
  • Save hratcliffe/ab180098d1ef3da1f3ba651c6cdf900f to your computer and use it in GitHub Desktop.
Save hratcliffe/ab180098d1ef3da1f3ba651c6cdf900f to your computer and use it in GitHub Desktop.
Variadic
#include<iostream>
// Needs C++14 for auto return type...
struct ST{
void theFn(int a){std::cout<<a<<std::endl;}
double theOtherFn(int a, double b){std::cout<<a<<" "<<b<<std::endl; return 0.0;}
void fnByRef(double & a){std::cout<<a<<std::endl;}
};
class wrapper{
ST theVal;
public:
//Forward
template<typename fn, typename ...Args>
auto invoke(fn callable, Args&&... args){ // Universal reference
return (theVal.*callable)(std::forward<Args>(args)...); // std::forward helps preserve reference, const etc
}
};
auto call_theFn(wrapper & theW, int theVal){
theW.invoke(&ST::theFn, theVal);
}
int main(){
wrapper myW;
auto fn = &ST::theFn;
myW.invoke(fn, 10); //Prints 10
call_theFn(myW, 7); //Prints 7
auto fn2 = &ST::theOtherFn;
myW.invoke(fn2, 1.0, 2.0); //Prints 1 2
auto fn3 = &ST::fnByRef;
//myW.invoke(fn3, 3.4); //Invalid - can't bind a value to a non-const reference
double x = 1.1;
myW.invoke(fn3, x);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment