Reputation: 5178
I have a template function for a class C
, and have two other template functions for typename T
, which I would like to use as shown below:
template <typename T>
std::string MyHelperFunction1(...) { ... }
template <typename T>
std::string MyHelperFunction2(...) { ... }
template <class C>
std::string MyFunction(...) {
// if C is an instance of Struct1<T> -> call MyHelperFunction1<Struct1<T>>
// if C is an instance of Struct2<T> -> call MyHelperFunction2<Struct2<T>>
Database db = OpenDatabase();
return MyFunction<C>(db, ...); // The same function but with different input args.
}
The closest question I found was this (How to check for the type of template parameter?), which doesn't work for my case, because I'm calling other template functions inside MyFunction()
. What's a working solution for what I want to have?
Upvotes: 0
Views: 192
Reputation: 598174
You can try using template specialization to decide which function to call, eg:
template <typename T>
struct helper {
static std::string MyHelperFunction(...) {
return "";
}
};
template <typename T>
struct helper<Struct1<T>> {
static std::string MyHelperFunction(...) {
return MyHelperFunction1<Struct1<T>>(...);
}
};
template <typename T>
struct helper<Struct2<T>> {
static std::string MyHelperFunction(...) {
return MyHelperFunction2<Struct2<T>>(...);
}
};
template <class C>
std::string MyFunction(...) {
helper<C>::MyHelperFunction(...);
...
}
Upvotes: 3
Reputation: 129
The idea is to write a helper to call proper function according to the type C
.
template <typename T>
auto MyFunctionHelper(Struct1<T> s, ...) { return MyHelperFunction1(s, ...); }
template <typename T>
auto MyFunctionHelper(Struct2<T> s, ...) { return MyHelperFunction2(s, ...); }
template <typename C>
std::string MyFunction(C c, ...){ return MyFunctionHelper<C>(c, ...); }
Upvotes: 1