小编Tra*_*ork的帖子

C++递归模板类型推导

我有兴趣学习一些关于模板元编程的知识.在下面的代码中,我试图找到一个足够大的无符号整数类型,用于保存在编译时指定的N位,使用一些模板递归.

template <typename T>
struct NextIntegralType
{
};

template <>
struct NextIntegralType<void>
{
    typedef unsigned char type;
};

template <>
struct NextIntegralType<unsigned char>
{
    typedef unsigned short type;
};

...More type 'iteration' here...

template<size_t BITS, typename T>
struct FindIntegralType2
{
    typedef std::conditional<BITS <= sizeof(typename T::type)*8, T, FindIntegralType2<BITS, NextIntegralType<typename T::type>>> _type;
    typedef typename _type::type type;
};

template<size_t BITS>
struct FindIntegralType
{
    typedef typename FindIntegralType2<BITS, NextIntegralType<void>>::type type;
};
Run Code Online (Sandbox Code Playgroud)

当我声明一个变量并为其赋值时...

FindIntegralType<15>::type test(4000);
Run Code Online (Sandbox Code Playgroud)

我得到以下内容:

error: no matching function for call to ‘FindIntegralType2<15u, NextIntegralType<unsigned char> …
Run Code Online (Sandbox Code Playgroud)

c++ recursion templates template-meta-programming

6
推荐指数
1
解决办法
802
查看次数