Without going into too much detail, I've created a variadic template function which does different things depending on the type of its template parameters. I simplified the implementation into a really simple console print example:
#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;
}
In the above code I call the variadic function with a const char*
and a char
. It works correctly, however the trouble is that the compiler gives me a warning:
[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...);
^~~~~~~~~~~~~~~~~~~~
The warning comes for the char
argument, as if the function incorrectly determined the type of char
to be the same as const char*
and therefore the code path for const char*
were triggered.
Why am I getting this warning and how do I fix it?
Thanks in advance for your answers!
Aucun commentaire:
Enregistrer un commentaire