C++11: Template Function Specialization for Integer Types

后端 未结 5 1514
挽巷
挽巷 2020-12-04 19:52

Suppose I have a template function:

template
void f(T t)
{
    ...
}

and I want to write a specialization for all primiti

5条回答
  •  长情又很酷
    2020-12-04 20:18

    What about a more straightforward and better readable way by just implementing the different versions inside the function body?

        template
        void DoSomething(T inVal) {
            static_assert(std::is_floating_point::value || std::is_integral::value, "Only defined for float or integral types");
            if constexpr(std::is_floating_point::value) {
                // Do something with a float
            } else if constexpr(std::is_integral::value) {
                // Do something with an integral
            }
        }
    

    You dont have to worry about performance. The conditions are compile time constant and a descent compiler will optimize them away. "if constexpr" is c++17 unfortunately but you may remove "constexpr" when both versions compile without errors for both types

提交回复
热议问题