check template type for type



  • Hey guys,

    I know, it's probably more a general c++ question than qt but anyway...

    I have a dll which provides functions like:

    bool GetDataAsU8(unsigned char *data)
    bool GetDataAsS16(short *data)
    bool GetDataAsU32(uint *data)
    ...
    

    I want to write a helper function which uses templates and selects the right imported dll function automatically.

    template <typename T> bool GetData(T *data)
    {
        //here I want to check the type of data and select the right function
    }
    

    Could someone help?
    Thanks in advance!

    mts


  • Moderators

    Hi,
    why can't you simply provide several overloaded versions of GetData() ?



  • You could use the typeid operator

    if (typeid(data) == typeid(uint)) {
    ...
    } 
    

  • Lifetime Qt Champion

    Hi,

    If you only want one function you could use the technique described here to "if" trough possible types.

    Otherwise, template specialization could also be an option

    Hope it helps


  • Moderators

    To check the type at runtime you can also use is_same template:

    #include <type_traits>
    template <typename T> bool GetData(T *data) {
        if(std::is_same<T, unsigned char>::value) return GetDataAsU8(data);
        //and so on for other types
    }
    

    but this is unnecessarily slow, so is the typeid solution.
    Template specialization, as suggested by @SGaist, is the way to go here.



  • Thanks for your answers!
    I think I will go with Template specialization.

    CU
    mts


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.