根据sizeof类型进行模板专业化 [英] template specialization according to sizeof type

查看:57
本文介绍了根据sizeof类型进行模板专业化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提供一个模板化函数,根据模板类型的大小来改变其实现(->专业化).

I would like to provide a templated function, that varies its implementation (->specialization) according to the sizeof the template type.

类似于此内容(省略了类型转换),但没有if/elseif:

Something similar to this (omitted typecasts), but without the if/elseif:

template<class T>
T byteswap(T & swapIt)
{
    if(sizeof(T) == 2)
    {
        return _byteswap_ushort (swapIt);
    }
    else if(sizeof(T) == 4)
    {
        return _byteswap_ulong(swapIt);
    }
    else if(sizeof(T) == 8)
    {
        return _byteswap_uint64(swapIt);
    }
            throw std::exception();
}

我知道有很多方法可以实现我的目标,但是由于我尝试学习 SFINAE type traits ,所以我对使用这些技术来解决问题的方法特别感兴趣在编译时决定选择哪个专业,哪些调用不被接受.

I know there are many roads to reach my goal, but since I try to learn about SFINAE and type traits I'm particularly interested in solutions using those techniques to decide at compile time which specialization to choose and which calls are not admitted.

也许实现类特征is_4ByteLong并使用boost :: enable_if ...

Perhaps implementing a class trait is_4ByteLong and using boost::enable_if...

我必须承认,我现在陷入困境,所以感谢您的帮助或建议

I have to admit, I'm stuck right now, so I thank you for any help or advice

推荐答案

您不需要SFINAE或键入traits.香草模板专业化就足够了.当然,它必须专门针对结构,因为C ++(98)不支持函数模板的部分专门化.

You don't need SFINAE or type traits. Vanilla template specialization is enough. Of course it must be specialized on structs as C++(98) doesn't support function template partial specialization.

template <typename T, size_t n>
struct ByteswapImpl
/*
{
  T operator()(T& swapIt) const { throw std::exception(); }
}
*/    // remove the comments if you need run-time error instead of compile-time error.
;

template <typename T>
struct ByteswapImpl<T, 2> {
  T operator()(T& swapIt) const { return _byteswap_ushort (swapIt); }
};

// ...

template <typename T>
T byteswap(T& swapIt) { return ByteswapImpl<T, sizeof(T)>()(swapIt); }

这篇关于根据sizeof类型进行模板专业化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆