简体   繁体   English

C ++使用模板为原始类型创建别名吗?

[英]C++ create aliases for primitive types using templates?

I'm trying to write some stuff to wrap simd intrinsics, and I figured that it would be nice to do something like 我正在尝试写一些东西来包装simd内部函数,我认为做这样的事情会很好

using vec<float, 4> = __m128;

so that I could use templates in some code I write later on. 这样我就可以在稍后编写的一些代码中使用模板。 This isn't really relevant to the question, but __m128 is a type that represents 4 floats. 这实际上与问题无关,但是__m128是代表4个浮点数的类型。 This doesn't work, and g++ says expected nested-name-specifier before 'vec' . 这是行不通的,并且g ++ expected nested-name-specifier before 'vec'说了expected nested-name-specifier before 'vec' I know I can just write classes to wrap them, or I can do something like: 我知道我可以编写类来包装它们,或者可以执行以下操作:

template <typename T, int N> struct vec;

template<> struct vec<float, 4>
{
    typedef __m128 type;
};

and then I can use vec<float,4>::type , but the first way is far more convenient. 然后我可以使用vec<float,4>::type ,但是第一种方法要方便得多。 I think it might be possible using something like C++ template typedef , but I'm not sure, and I wouldn't know the syntax. 我认为可以使用C ++模板typedef之类的东西,但是我不确定,我也不知道语法。 Is there any way to make the first statement work or to do something similar? 有什么方法可以使第一条语句起作用或做类似的事情?

No, the first can't work. 不,第一个不能工作。 It doesn't make sense given the current rules (you can't hijack the syntax of a template like that). 鉴于当前规则,这没有任何意义(您无法劫持这样的模板的语法)。

Your second solution however is perfect! 但是,您的第二个解决方案是完美的! You just need to make a slight adjustment: 您只需要稍作调整:

namespace impl {
    template <typename T, int N> struct vec;

    template<> struct vec<float, 4>
    {
        typedef __m128 type;
    };
}

template<typename T, int N>
using vec = typename impl::vec<T, N>::type;

Now vec is an actual template referring to the type of the corresponding struct. 现在, vec是一个实际的模板,它引用相应结构的type

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

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