fengqi
fengqi

Reputation: 377

Why isn't the expected function called? Do I understand type traits incorrectly?

I am trying to learn the concept of type traits. And I wrote some code to test my understanding:

#include <iostream>
#include <typeinfo>
#include <utility>

class Normal1 {};
class Normal2 {};
class Special {};

struct Normal_tag {};
struct Special_tag {};

template <typename T>
struct trait {
    typedef Normal_tag Type;
};

template <>
struct trait<Special> {
    typedef Special_tag Type;
};

template <typename T>
void handle_impl(T&& object, Normal_tag) {
    std::cout << "normal called\n";
}

template <typename T>
void handle_impl(T&& object, Special_tag) {
    std::cout << "special called\n";
}

// method 1: can't pass in rvalue
// template <typename T>
// void handle(T& object) {
//     handle_impl(object, typename trait<T>::Type());
//     std::cout << '\t' << typeid(T).name()                       << '\n'
//               << '\t' << typeid(typename trait<T>::Type).name() << '\n';
// }

// method 2: always lvalue
// template <typename T>
// void handle(const T& object) {
//     handle_impl(object, typename trait<T>::Type());
//     std::cout << '\t' << typeid(T).name()                       << '\n'
//               << '\t' << typeid(typename trait<T>::Type).name() << '\n';
// }

// method 3: try to use universal reference
template <typename T>
void handle(T&& object) {
    // handle_impl(object, typename trait<T>::Type());
    handle_impl(std::forward<T>(object), typename trait<T>::Type());
    std::cout << '\t' << typeid(T).name()                       << '\n'
              << '\t' << typeid(typename trait<T>::Type).name() << '\n';
}

int main(int argc, char *argv[])
{
    Normal1 n1;
    Normal2 n2;
    Special sp;

    handle(sp);                 // This line
    handle(n1);
    handle(n2);

    handle(Special());
    handle(Normal1());
    handle(Normal2());

    return 0;
}

The output below is not what I expected, I want the special method to be call for both lvalue and rvalue arguments:

normal called
        7Special
        10Normal_tag
normal called
        7Normal1
        10Normal_tag
normal called
        7Normal2
        10Normal_tag
special called
        7Special
        11Special_tag
normal called
        7Normal1
        10Normal_tag
normal called
        7Normal2
        10Normal_tag

I think the output means that the class Special is used for instantiation. But why do I get Normal_tag? Why is the call handle(sp); behaving this way?

I was hoping the universal reference will take care of both lvalue and rvalue argument, is this a bad way?

Upvotes: 0

Views: 48

Answers (1)

rafix07
rafix07

Reputation: 20969

When you call handle(sp); sp is L-value, so in your handle template T is deduced to be Special& but you don't have specialization for Special&

template <>
struct trait<Special&> {
   typedef Special_tag Type;
};

therefore you got normal called as output.

Upvotes: 3

Related Questions