无需赘述,我创建了一个可变参数模板函数,该函数根据其模板参数的类型执行不同的操作。我将实现简化为一个非常简单的控制台打印示例:
#include <cstdint>
#include <cstddef>
#include <cstdio>
#include <cstring>
#include <type_traits>
void print(const char *chars) {
printf("%s", chars);
}
template<typename FirstType, typename ... OtherTypes>
inline void print(FirstType first, OtherTypes... others);
template<typename ... OtherTypes>
inline void print(const char *chars, OtherTypes... others) {
print(chars);
print(" ");
if (sizeof...(others) == 0) {
print("\r\n");
}
else {
print(others...);
}
}
template<typename FirstType, typename ... OtherTypes>
inline void print(FirstType first, OtherTypes... others) {
char buffer[10];
const char *format = nullptr;
if (std::is_same<int, FirstType>::value) {
format = "%d";
}
else if (std::is_same<char, FirstType>::value) {
format = "%c";
}
else if (std::is_pointer<FirstType>::value && (std::is_same<char*, FirstType>::value || std::is_same<const char*, FirstType>::value)) {
print((const char *) first, others...);
return;
}
if (format != nullptr) {
snprintf(buffer, 10, format, first);
}
print((const char *) buffer, others...);
}
int main() {
print("this is an example:", 'X');
return 0;
}
在上面的代码中,我使用aconst char*
和a调用可变参数函数char
。它可以正常工作,但是麻烦的是编译器向我发出警告:
[Timur@Timur-Zenbook tm]$ g++ tm.cpp -Wall -Wextra -o tm
tm.cpp: In instantiation of ‘void print(FirstType, OtherTypes ...) [with FirstType = char; OtherTypes = {}]’:
tm.cpp:24:14: required from ‘void print(const char*, OtherTypes ...) [with OtherTypes = {char}]’
tm.cpp:52:37: required from here
tm.cpp:40:15: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
print((const char *) first, others...);
^~~~~~~~~~~~~~~~~~~~
该char
参数发出警告,好像该函数错误地确定的类型char
与相同const char*
,因此const char*
触发了其代码路径。
为什么会收到此警告,该如何解决?
预先感谢您的回答!
为什么我收到此警告
即使实际上不会执行该分支,该分支中的代码仍会在is时实例化。FirstType
char
我如何解决它?
将仅对某些类型有意义的代码移到重载或特殊特征中,这样就不会针对不匹配的类型首先编译该代码。
最简单的更改是else if(std::is_pointer...
完全删除分支,并添加此重载,其效果相同:
template<typename ... OtherTypes>
inline void print(char *chars, OtherTypes... others) {
print((const char *)chars, others...);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句