manatttta manatttta - 22 days ago 8
C++ Question

Function template specialization

I am trying to create a function template with a default implementation and some specializations as follows:

template <typename T>
inline T fromBool(bool var) { return var ? T(1) : T(0); }

template <>
inline Vec2 fromBool<Vec2>(bool var) { return var ? Vec2(1, 1) : Vec2(0, 0); }

// Some more specializations for Vec3, etc


This is an example definition of the complex type
Vec2
:

struct Vec2 {
double x, y;
Vec2(double a, double b) { x = a; y = b; }


However, the specialization is not working. When I call
fromBool<Vec2>(var)
, the compiler uses the default implementation (the one for simple types).

What am I doing wrong?

Answer

From your comment, it seems like you want a version which should work with both Vec2 and const Vec2

template <typename T>
struct fromBool_impl {
    static T fromBool(bool var) { return var ? T(1) : T(0); }
};
template <>
struct fromBool_impl<Vec2> {
    static Vec2 fromBool(bool var) {
        return var ? Vec2(1, 1) : Vec2(0, 0);
    }
};

template <typename T>
inline T fromBool(bool var) {
    return fromBool_impl<typename std::remove_cv<T>::type>::fromBool(var);
}

int main() {
    fromBool<Vec2>(true);
    fromBool<const Vec2>(true);
}

Note: if T is reference type, the behavior is undefined.


The above code use std::remove_cv from C++11, it's not hard to implement it in C++98, you can find one possible implementation from std::remove_cv