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;
}
auto lambda = [](const auto& data) { func(data); }; enumerate(lambda);?if constexprwith traits likestd::is_same_v. Whatever you do do NOT usetypeid(T)that is a runtime thing.funcis passed in asdata, so to access the argument, you usedata. You should re-write your question to focus on the second formulation of your goal.