Search code examples
c++templatestemplate-specializationtype-traits

With C++ type-traits, is there some way to avoid casting


Say I use C++ type-traits in a method template to check if T is double, is there some way I can treat variables of type T as double, without doing a cast?

T *l_double; //T is double 
if T is of type double 
   auto a = 5 * (*l_double);

(This will fail because T can be a non-number type, I could solve it by casting, but would like to avoid it).


Solution

  • If I understand your question correctly, what you want to have is a specialization for the case of T being double. Well, just do that - no type traits involved:

    template <typename T>
    void foo(T x) { /* do something with x */ }
    
    template <>
    void foo<double>(double x) { /* do something _else_ with x */ }
    

    Or if you use C++17, you can also do:

    template <typename T>
    void foo(T x) { 
        if constexpr (not std::is_same_v<double,T>) {
            /* do something with x */ 
        }
        else {
            /* do something with else x */ 
        }
    }
    

    Note the constexpr after the if. That means the code within each block only gets compiled for the appropriate instantiations; without it, you can't use x as a double in the else block since that use would have to also work when x is of another type.