jeudi 2 mars 2017

Variadic template chooses more common template instead of overload

Imagine this code:

#include <iostream>
void PrintInternal() {
    std::cout << std::endl;
}

template <typename T, typename...ARGS>
void PrintInternal(const T& head, const ARGS&...rest) {
    std::cout << head << " ";
    PrintInternal(rest...);
};

template <typename...ARGS>
void PrintInternal(const double& head, const ARGS&...rest) {
    std::cout << "DBL!!! " << head << " ";
    PrintInternal(rest...);
}

template <typename...ARGS>
void Print(const ARGS&...args) {
    PrintInternal(args...);
}

int main() {
    Print(1.1, 2, 3.3, 4);
    Print(0, 1.1, 2, 3.3, 4);
    return 0;
}

First Print outputs:

DBL!!! 1.1 2 3.3 4

My expectations were, that it would output DBL!!! before 3.3 or no DBL!!! at all. But why one???

Second Print outputs:

0 1.1 2 3.3 4

Why there is no DBL!!! output like at all, if we had one in first example.

And how to achieve, that for each double I will output something different without partial specialization? I've thought, that simple overloading should be ok...

Link to cpp.sh to view compilation results -> http://cpp.sh/42cz

Aucun commentaire:

Enregistrer un commentaire