实现自定义sizeof运算符

时间:2015-12-18 01:06:00

标签: c++ sizeof

我正在开发一个用于创建自定义大小的整数的类,比如3,5,6,7个字节,并且需要一个自定义sizeof运算符,当它获得csnumeric类型时会调用SizeOf函数,否则使用内置的sizeof运算符。

如果我在typename上使用sizeof_x_is_type宏,或者如果我在变量上使用sizeof_x_is_variable,它的效果非常好,我的问题是我似乎无法创建一个可以处理类型名和变量并调用相应函数的宏。 / p>

我似乎无法找到区分typename或variable的方法。 我最接近的是is_variable()函数,它可以使用模板参数区分typename或integer。

根据我们是否获得typename或变量,有没有办法调用不同的函数?

编辑:

我需要自定义sizeof所以我可以使用我的自定义整数类型和一个使用sizeof读取和写入缓冲区的类

template<typename T, uint8 Size, T Mask>
class csnumeric : public csnumeric_base
{
    private:

       static uint8 constexpr m_Size = Size; 

    public:

       static constexpr uint8 SizeOf() noexcept { return m_Size; }

    rest of code goes here...
}

using int56 = csnumeric<int64, 7, 0x00FFFFFFFFFFFFFF>;
using int48 = csnumeric<int64, 6, 0x0000FFFFFFFFFFFF>;
using int40 = csnumeric<int64, 5, 0x000000FFFFFFFFFF>;
using int24 = csnumeric<int32, 3, 0x00FFFFFF>;
using uint56 = csnumeric<uint64, 7, 0x00FFFFFFFFFFFFFF>;
using uint48 = csnumeric<uint64, 6, 0x0000FFFFFFFFFFFF>;
using uint40 = csnumeric<uint64, 5, 0x000000FFFFFFFFFF>;
using uint24 = csnumeric<uint32, 3, 0x00FFFFFF>;

template<typename T>
constexpr typename std::enable_if<std::is_base_of<csnumeric_base, T>::value, std::size_t>::type csnumeric_sizeof() noexcept { return T::SizeOf(); }

template<typename T>
constexpr typename std::enable_if<!std::is_base_of<csnumeric_base, T>::value, std::size_t>::type csnumeric_sizeof() noexcept { return sizeof(T); }

template<typename T>
constexpr bool is_variable() noexcept { return false; }

template<uint32 T>
constexpr bool is_variable() noexcept { return true; }

#define sizeof_x_is_type(x) csnumeric_sizeof<x>()
#define sizeof_x_is_variable(x) csnumeric_sizeof<decltype(x)>()
#define sizeof_custom(x) ( is_variable<x>() ? sizeof_x_is_variable(x) : sizeof_x_is_type(x) )

0 个答案:

没有答案
相关问题