'Using type traits in C++ template functions, is it possible to convert a value to a T of the same type?

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++?



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anoop Rana