lundi 19 août 2019

What does this "template

In the following code sample:

template<typename T>
struct Foo
{
    template<typename U = T>
    typename std::enable_if<std::is_same<U, int>::value>::type
    MyFunction()
    {
        std::cout << "T is int." << std::endl;
    }

    template<typename U = T>
    typename std::enable_if<std::is_same<U, float>::value>::type
    MyFunction()
    {
        std::cout << "T is not int." << std::endl;
    }
};

What is the point of the template<typename U = T> part?

When we create an instance of Foo, with a type int, the T will be int. Now we have another type U, which is equal to T. Therefore, it is int as well. (The same applies for any other provided type.) It looks like a redundant part of code, because T=U=int. But, if I remove the template<typename U = T>, the code will not compile (U was replaced with T in is_same in that case).

Can somebody in detail explain what it going on here in compile time?

I'm not interested in answers like "That's SFINAE, that's how SFINAE works". Answers like that are useless.

Aucun commentaire:

Enregistrer un commentaire