简体   繁体   中英

Check for the type of a template parameter and use another template

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?

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(...);
    ...
}

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, ...); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM