根据sizeof类型的模板特化

nab*_*lke 18 c++ templates

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

类似的东西(省略了类型转换),但没有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();
}
Run Code Online (Sandbox Code Playgroud)

我知道有很多道路可以实现我的目标,但是自从我尝试了解SFINAE并且type traits我对使用这些技术的解决方案特别感兴趣,在编译时决定选择哪种特殊化以及哪些呼叫不被接纳.

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

我不得不承认,我现在卡住了,所以我感谢你提供任何帮助或建议

ken*_*ytm 20

您不需要SFINAE或类型特征.香草模板专业化就足够了.当然它必须专门用于结构体,因为C++(98)不支持函数模板部分特化.

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); }
Run Code Online (Sandbox Code Playgroud)

  • 很好的答案,但我不会做`ByteswapImpl`的默认实现.这样,如果不存在所需的特化,您将只会遇到编译错误. (6认同)