c++ - 提取模板类型的签名?

标签 c++ templates unsigned signed

下面的代码使用 -Wsign-conversion 生成警告。它在 T digit = a % base 行生成警告。

我想提取 T 的签名,然后将 base 转换为该签名以消除警告。

我试图避免专门化,因为那只会重复代码(唯一要改变的是 base 的签名)。我还试图避免将 base 转换为 T 以防它是非 POD 类型,如 Integer (针对使用 longs 减少)。

如何提取 T 的符号性?


相关的,代码库实际上是 C++98 和 C++03,因此它没有一些功能(如 Partial template specialization based on “signed-ness” of integer type? 中讨论的)。


template <class T>
std::string IntToString(T a, unsigned int base = 10)
{
    if (a == 0)
        return "0";
    bool negate = false;
    if (a < 0)
    {
        negate = true;
        a = 0-a;    // VC .NET does not like -a
    }
    std::string result;
    while (a > 0)
    {
        T digit = a % base;
        result = char((digit < 10 ? '0' : ('a' - 10)) + digit) + result;
        a /= base;
    }
    if (negate)
        result = "-" + result;
    return result;
}

最佳答案

C++11 之前你可以使用 std::conditional 的这个实现:

template<bool B, class T, class F>
struct conditional { typedef T type; };
template<class T, class F>
struct conditional<false, T, F> { typedef F type; };

然后我们可以编写一个结构来提取类型的符号:

template <typename T>
struct signedness {
    typedef typename conditional<T(-1)<T(0),int,unsigned>::type type;   
};

然后只需将 base 声明为该类型即可:

std::string IntToString(T a, 
    typename signedness<T>::type base = 10){

关于c++ - 提取模板类型的签名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31241077/

相关文章:

c++ - 为什么会出现错误 "no matching function for call to ' A(A<...auto...> )'"?

c++ - 理解(简单?)C++ 部分模板特化

c - 为什么C语言中每一个signed int类型都必须有一个对应的unsigned int类型?

C++模板重构/泛化

c++ - 如何在 if () 语句中声明变量?

c++ - 从中序和先序遍历构造二叉树的时间复杂度

templates - 使用 Umbraco 7.2 GridView ,如何将 GridView 插入到我的模板中?

c++ - 负常量的后缀(或后缀)U、UL、ULL

C# Convert.ToInt16(String) C 等价物

c++ - 从 C 中的文本文件中读取特定列的数据