0

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?

Matin Kh
  • 5,192
  • 6
  • 53
  • 77
  • I would avoid `...` which has special meaning (C-ellipsis or variadic template). – Jarod42 Jan 15 '21 at 01:36
  • Thank you, Jarod. Although in this case I don't think it can be read in any other way, I agree that it has actual meanings and might create confusion. I'll keep that in mind for my future posts. (the reason I'm not changing the question now, is that the answers follow the same style. Changing the question might create more confusion, than reducing them) – Matin Kh Jan 15 '21 at 02:36

2 Answers2

3

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(...);
    ...
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
1

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, ...); }
Shuchang
  • 129
  • 3