Plebshot
Plebshot

Reputation: 220

Specialize a template class to behave like a float in one case

So, imagine a vector class:

template <size_t size>
class Vector<size> {
    std::array<float, size> data;
    .... 
}

Is there a way to specialize the template to be a float if the size is 1? Something like:

// The case of a Vector with size 1 should behave like a float
template <>
using class Vector<1> = float; 

I want to apply that to other classes too. For example, treating a Matrix with column size 1 to be a Vector with the size of its rows.


Thanks in advance for the help :)

Upvotes: 1

Views: 89

Answers (3)

W.F.
W.F.

Reputation: 13988

Your original code would probably violate One-Definition Rule, but I believe this could be fairly equivalent and relatively short alternative:

template <std::size_t N>
struct VectorImpl {
   std::array<float, N> data;
};

template <std::size_t N>
using Vector = typename std::conditional<(N == 1), float, VectorImpl<N>>::type;

[live demo]

Upvotes: 0

user7860670
user7860670

Reputation: 37600

You can use a dedicated template for type selection (note that partial specializations are not permitted for alias templates so there is no way to get away with just one template):

template<size_t size> struct
VectorType{ using type = VectorImpl<size>; }; // VectorImpl is your current Vector

template<> struct
VectorType<1>{ using type = float; };

// alias template
template<size_t size> using
Vector = typename VectorType<size>::type;

Upvotes: 6

3CxEZiVlQ
3CxEZiVlQ

Reputation: 38773

I can not check it right now. Maybe in a way like below.

template <>
class Vector<1> {
  float n;
 public:
  operator float& () { return n; }
}

May be you need implement other required operators.

Upvotes: 2

Related Questions