#include <iostream>
#include <string>
template<typename Func>
class FuncWrapper {
Func func;
std::string name;
public:
FuncWrapper(Func func, std::string name) : func(func), name(std::move(name)) {}
template<typename ...Args>
auto operator()(Args ...args) {
std::cout << "Entering " + name + '\n';
func(args...);
std::cout << "Exiting " + name + '\n';
}
};
template<typename Func>
auto makeFuncWrapper(Func func, std::string name) {
return FuncWrapper<Func>(func, name);
}
int main() {
auto helloWorld = []() { std::cout << "Hello World\n"; };
auto printTwoNums = [](int a, int b) { std::cout << a << ' ' << b << '\n'; };
// FuncWrapper(helloWorld, "helloWorld")(); // Error.
// FuncWrapper(printTwoNums, "printTwoNums")(4, 5); // Error.
makeFuncWrapper(helloWorld, "helloWorld")();
std::cout << '\n';
makeFuncWrapper(printTwoNums, "printTwoNums")(4, 5);
}
Output:
Entering helloWorld
Hello World
Exiting helloWorld
Entering printTwoNums
4 5
Exiting printTwoNums
I'm trying to make a function wrapper that adds an additional functionality to a function. In the class FuncWrapper
, there is a field called func
with the type of the template argument (Func
). When I try to pass a lambda to the constructor, I get an error saying that I'm missing some template arguments. Whereas if I use a helper function, it deduces the type normally. Why isn't it deducing the type of the argument when I pass the lambda to the constructor? And why the function can deduce but not the constructor of a class? Also what is a possible solution? And is there any possible improvement to this code or a better way to achieve the same behavior?