Reputation: 220
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
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;
Upvotes: 0
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
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