vendredi 31 août 2018

How to detect type of uint8_t in parameter pack

#include <iostream>
#include <type_traits>

template<class Head>
void print_args(std::ostream& s, Head&& head) {
    s << std::forward<Head>(head);
}

template<class Head, class... Tail>
void print_args(std::ostream& s, Head&& head, Tail&&... tail) {
    if (std::is_same<Head, uint8_t>::value)
        s << static_cast<int>(head) << ",";       // cast uint8_t so that the value of 1 or 0 can be displayed correctly in console
    else
        s << std::forward<Head>(head) << ",";
    print_args(s, std::forward<Tail>(tail)...);
}

template<class... Args>
void print_args(Args&&... args) {
    print_args(std::cout, std::forward<Args>(args)...);
}

int main()
{
    uint8_t val = 1;
    print_args(std::string("hello"), val); // error: invalid static_cast from type 'std::basic_string<char>' to type 'int'
    print_args("hello", val); // error: invalid static_cast from type 'const char [6]' to type 'int'
}

Question> I need to cast uint_8 to int so the value can be displayed correctly in console. However, the above code has build issue for either std::string or const char*.

What is the fix for the function?

Aucun commentaire:

Enregistrer un commentaire