Home > Software design >  Using a C fundamental type as a class template specialization
Using a C fundamental type as a class template specialization

Time:12-25

I have a template class for D-dimensional 'geometrical' vectors:

template <size_t D>
class Vector;

I would like to use the float fundamental type as the 1-dimensional specialization of this template class.

Is it possible to define such a specialization? The naïve approach

template<> using Vector<1> = float;

does not compile

CodePudding user response:

You cannot use an existing type in place of a specialization, but you can use a typedef to do the switching:

template <std::size_t D>
class Vector_impl { };

template <std::size_t D>
using Vector = std::conditional_t<
    D == 1,
    float,
    Vector_impl<D>
>;

static_assert(std::is_same_v<Vector<1>, float>);
static_assert(std::is_same_v<Vector<2>, Vector_impl<2>>);

You could also use an intermediate type trait to perform more advanced selection logic (à la template <std::size_t D> using Vector = typename Vector_selector<D>::type).

CodePudding user response:

You can use

template<>
class Vector<1>

To achieve the behavior you are looking for.

See: https://godbolt.org/z/T7ME65Wv1 for a trivial example.

If you are wanting to conditionally choose the underlying storage type, you can do this

template <size_t D>
class Vector
{
    using type = std::conditional_t<D == 1, float, T>; //T is your choice.
public:
    type data[D];
};

See:
https://godbolt.org/z/fMKMrh7Ex

  • Related