Search code examples
c++c++11rttiperfect-forwarding

Does it make sense to use std::forward with the typeid operator?


I was wondering whether it makes sense to use std::forward<> when submitting an instance to typeid?

template <typename T>
void foo(T&& value) {
  std::cout << typeid(std::forward<T>(value)).name() << std::endl;
}

Does invoking typeid(value) instead yields the same result?


Solution

  • From [expr.typeid]/3:

    When typeid is applied to an expression other than a glvalue of a polymorphic class type, the result refers to a std::type_info object representing the static type of the expression.

    In the C++ Standard, the "type of an expression" is never a reference type; the "reference-ness" (lvalue or rvalue reference) of an expression is expressed in its value category. Since std::forward does not modify the type of an expression, only its value category (e.g. from lvalue to rvalue), applying std::forward will not affect the result of typeid.