无效的静态强制转换

Invalid Static Cast

本文关键字:转换 静态 无效      更新时间:2023-10-16

我从这里获取了代码:

http://en.wikipedia.org/wiki/Variadic_template

然而,它将uint8_t和int8_t视为ASCII,因此我想将任何为int16_t的内容强制转换。我试着这样做:

template<typename T, typename... Args>
void log(const char *s, T value1, Args... args)
{
while (*s) {
    if (*s == '%') {
        if (*(s + 1) == '%') {
            ++s;
        }
        else {
        if ( std::is_same<T, uint8_t>::value || std::is_same<T, int8_t>::value )
        {
            int16_t x = value1;
            int16_t x = static_cast<int16_t>(value1);
            std::cout << x;
        }
        else
        {
           std::cout << value1;
        }
            log(s + 1, args...); // call even when *s == 0 to detect extra arguments
            return;
        }
    }
    std::cout << *s++;
}
throw std::logic_error("extra arguments provided to printf");
}

然而,我得到了错误:

error: invalid static_cast from type ‘std::basic_string<char, std::char_traits<char>,  
std::allocator<char> >’ to type ‘int16_t’

有没有不打印ASCII?

If语句不进行编译时决策;编译器将始终检查两个分支。

您需要创建一个重载的write()函数,其中默认版本流到cout,并且您可以为特定类型(如char)重载该函数。

问题:

就像你的编译器说的:

error: invalid static_cast from type ‘std::basic_string<char, std::char_traits<char>,  
std::allocator<char> >’ to type ‘int16_t’

我想你调用日志函数是这样的:

log("my % thing %....", /*my std::string*/ stringToto, 5,/*....*/);

问题来了!

当编译器看到您要从static_caststd::string再到int16_t时,它会生成一个错误!

你做错了什么

本部分:

    if ( std::is_same<T, uint8_t>::value || std::is_same<T, int8_t>::value )
    {
        int16_t x = value1;
        int16_t x = static_cast<int16_t>(value1);
        std::cout << x;
    }
    else
    {
       std::cout << value1;
    }

为什么?事实上,即使条件(std::is_same<T, uint8_t>::value || std::is_same<T, int8_t>::value)为false,编译器也会解释static_cast

你该怎么办

使用一个函数获取一个参数(无论其类型如何)并生成一个std::字符串,如下所示:

template<typename T>
std::string
my_to_string(T) { return ("what is this type?"); }
template<>
std::string
my_to_string(std::string s) { return (s); }
template<>
std::string
my_to_string(int integer) { return (std::to_string(integer)); }

然后在日志函数中这样调用它:std::cout<lt;my_to_string(值1);

祝你工作顺利

您似乎使用无法转换为int16_tstd::string来调用函数。您可以使用以下为字符串重载的函数模板来代替static_cast

template<typename T>
auto cast_to_int(T const& t) -> int16_t
{
    return static_cast<int16_t>(t);
}
auto cast_to_int(std::string const& t) -> int16_t
{
     std::istringstream ss(Text);
     int16_t result;
     ss >> result;
     return result;
}

最终,您必须为其他类型重载它。


通过拨打上述电话

std::cout<< cast_to_int(value1);

而不是整个块

    if ( std::is_same<T, uint8_t>::value || std::is_same<T, int8_t>::value )
    {
        int16_t x = value1;
        int16_t x = static_cast<int16_t>(value1);
        std::cout << x;
    }
    else
    {
       std::cout << value1;
    }