I am working on a C++ function template and I am trying to find a way to access the function arguments within the template. Specifically, I have a template function called enumerate that takes a callable object as an argument.
※ However, I am unable to modify the generated code for the enumerate function.
Here is an example of the enumerate function:
template <typename F> void enumerate(F &func) noexcept(false) {
vector<int> a{1, 2, 3, 4};
int b = 10;
func(a);
func(b);
}
example code could be
#include <iostream>
#include <vector>
using namespace std;
template <typename T> void func(const T &data) {
cout << "hello " << typeid(T).name() << endl;
}
template <typename F> void enumerate(F &func) noexcept(false) {
vector<int> a{1, 2, 3, 4};
int b = 10;
func(a);
func(b);
}
int main() {
enumerate(func);
return 0;
}
I want to be able to handle different types of arguments, such as vectors and integers, within the func callable object. How can I achieve this without modifying the generated code for the enumerate function? Are there any techniques or approaches that I can use to access and process the function arguments within the function template?
Any help or guidance would be greatly appreciated. Thank you in advance.
below code could not deduce template parameter from compile side.
template <typename T> void func(const T &data) {
cout << "hello " << typeid(T).name() << endl;
}
You can pass a generic lambda instead of using a function template:
Unlike the function template, this works because you are passing an object of some non-templated closure type. The call operator of this closure type is a template, which allows you to pass objects of different types.