Passing functions as arguments in C++

You can use std::function to provide such template:

#include <iostream>
#include <functional>
#include <string>
#include <type_traits>

void convert_inplace(std::string& mystr){}
std::string convert(const std::string& mystr){
    return mystr;
}
void bitrot_inplace(std::string& mystr){}

template<typename ret, typename par>
using fn = std::function<ret(par)>;

template<typename ret, typename par>
void caller(fn<ret,par> f) {
    typename std::remove_reference<par>::type p;
    ret r = f(p);
}

template<typename par>
void caller(fn<void,par> f) {
    typename std::remove_reference<par>::type p;
    f(p);
}

int main() {
    auto f1 = fn<void,std::string&>(convert_inplace);
    auto f2 = fn<std::string,const std::string&>(convert);
    auto f3 = fn<void,std::string&>(bitrot_inplace);
    caller(f1);
    caller(f2);
    caller(f3);
    return 0;
}

See the live demo.


The easiest way, IMO, is to use a template instead of trying to write a function with a concrete type.

template<typename Function>
void printtime_inplace(string title, Function func)
{
    //...
    func(title);
    //...
}

This will now allow you to take anything that is a "function". You can pass it a regular function, a functor, a lambda, a std::function, basically, any callable. The compiler will stamp out different instantiations for you but as far as your code is concerned you are calling the same function.