简体   繁体   English

使用 C++ 基本类型作为类模板特化

[英]Using a C++ fundamental type as a class template specialization

I have a template class for D-dimensional 'geometrical' vectors:我有一个 D 维“几何”向量的模板类:

template <size_t D>
class Vector;

I would like to use the float fundamental type as the 1-dimensional specialization of this template class.我想使用float基本类型作为该模板类的一维特化。

Is it possible to define such a specialization?是否可以定义这样的专业化?

You cannot use an existing type in place of a specialization, but you can use a typedef to do the switching:您不能使用现有类型代替特化,但可以使用 typedef 进行切换:

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 ).您还可以使用中间类型特征来执行更高级的选择逻辑( à la template <std::size_t D> using Vector = typename Vector_selector<D>::type )。

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.有关简单示例,请参见: https ://godbolt.org/z/T7ME65Wv1。

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 https://godbolt.org/z/fMKMrh7Ex

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM