使用算术运算符时如何避免从 char 到 int 的隐式转换

How to avoid implicit conversion from char to int when using arithmetic operators

我已经为 intchar 制作了一些我想专门使用的代码模板。在这段代码中,我使用算术运算符 operator+。当我使用 g++ 编译时(转换警告,警告被视为错误)编译器抱怨我的 chars 被隐式转换为 ints 并且每个进一步的分配都会触发缩小转换警告。

下面是重现此问题的一些基本代码:

template<typename T>
T add(const T a, const T b)
{
    return a + b;
}

int main()
{
    const char a = 1;
    const char b = 2;

    const char c = add<char>(a, b); // a and b implicitely converted to int.
                                    // Assignement to c fails (narrowing)

    (void)c;

    return 0;
}

你可以编译(它应该会失败)使用:

g++ -Wconversion -Werror main.cpp

我知道这是因为定义了 operator+ 的最小内置类型是 int,所以当您使用较小的类型时,它们会自动转换以适应参数。

我正在寻找一种方法来避免这种情况并尽量减少转换。例如,我知道我可以将 ab 添加到 char 的结果转换为 char,但是对于包含很多项的添加,很快就会变得一团糟。

我该怎么做?


我得到的错误:

main.cpp:4:16: error: conversion to ‘char’ from ‘int’ may alter its value [-Werror=conversion]
     return a + b;
                ^
cc1plus: all warnings being treated as errors

所以是的,正式 this is the case:

... arithmetic operators do not accept types smaller than int as arguments, and integral promotions are automatically applied after lvalue-to-rvalue conversion [...]

但是您为什么要改变或避免这种行为?如果你像你建议的那样做,并且可能像这样投射 return 值:

template<typename T>
T add(const T a, const T b)
{
    return static_cast<T>(a + b);
}

比起 integer overflow 在 returned char 中的风险要快得多,因为它一开始就很小。您是否有任何理由避免在您的场景中进行促销?