无效的静态强制转换
Invalid Static Cast
我从这里获取了代码:
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_cast
到std::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_t
的std::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;
}
相关文章:
- enable_if转换构造函数(静态强制转换,is_base_of)
- 使用转换器提升 Python 问题 - 静态链接
- 不要使用静态强制转换进行算术转换(cpp-core-guidelines)
- C++实用程序::转换在静态链接库中不起作用
- 静态成员变量不会由 gettext 转换
- C++ 将静态方法转换为简单方法
- 虚拟成员函数的定义是否强制在同一转换单元中动态初始化静态数据成员?
- 如何使用静态多态性在 int 和指针类型之间进行转换?
- 指向 POD 类型的指针之间的静态转换与重新解释转换
- 静态强制转换内的表达式
- 了解类构造函数的静态强制转换
- 如何对以下程序使用静态或动态转换
- 我需要静态转换我的数字模板值吗
- 引用的静态强制转换强制模板实例化,其中不完整的类型很好
- 为什么静态向下转换unique_ptr不安全?
- 将私有结构哈希器运算符转换为静态
- 使用静态转换,因为动态转换失败.不好的做法?
- 尝试向 COM 对象添加另一个接口时出现静态强制转换错误 C2440
- 如何在预处理器 (#if) 中强制转换静态 const 以避免溢出
- 转换静态哈希表到动态哈希表