Home > Software engineering >  Using type traits in C template functions, is it possible to convert a value to a T of the same ty
Using type traits in C template functions, is it possible to convert a value to a T of the same ty

Time:03-03

I'm trying to write a template function like this

template<typename T>
T doSomething() { 
    //Code

    if (std::is_same<T, int>::value) { 
        return getInt();   // A library function returning an int
    } else if (std::is_same<T, bool>::value) {
        return getBool();  // A library function returning a bool
    } else { 
        throw;
    }
}

that calls different functions depending on the template parameter given and returns a value which, at runtime, is guaranteed to have the same type as T. However, the compiler gives me this error: 'return': cannot convert from 'int' to 'T' I guess I could use something like reinterpret_cast, but this seems to be unsafe and bad practice in this scenario.

So, is there a way to return different types from a template function depending on the template parameter in C ?

CodePudding user response:

So, is there a way to return different types from a template function depending on the template parameter in C ?

Yes, you can use C 17 constexpr if

template<typename T>
T doSomething() { 
    //Code

    if constexpr (std::is_same<T, int>::value) { 
        return getInt();   // A library function returning an int
    } else if constexpr (std::is_same<T, bool>::value) {
        return getBool();  // A library function returning a bool
    } else { 
        throw;
    }
}

CodePudding user response:

Besides constexpr if(for pre-c 17) you can also use explicit specialization as shown below:

template<typename T> //primary template
T doSomething() { 
    std::cout<<"throw version"<<std::endl;
    throw;
}

template<> //specialization for int
int doSomething<int>() { 
    std::cout<<"int version"<<std::endl;
    return getInt();
}

template<>//specialization for bool
bool doSomething<bool>() { 
    std::cout<<"bool version"<<std::endl;
    return getBool();
}

Demo.

  • Related