0

In this answer from this question the author posted this code:

 template <typename... Ts>
    typename std::tuple_element<0, std::tuple<Ts...> >::type // or decltype(auto) 
        callFunction(Ts&&... ts)
    {
        using type = typename std::tuple_element<0, std::tuple<Ts...> >::type;
        auto it = multiCache.find(typeid(type));
        assert(it != multiCache.end());
        auto&& fn = boost::any_cast<const std::function<type(Ts...)>&>(it->second);
        return fn(std::forward<Ts>(ts)...);
    }

The meaning of typename std::tuple_element<0, std::tuple<Ts...> >::type is that the returned type is the same of the first element of the first element in Ts..., right?

Community
  • 1
  • 1
justHelloWorld
  • 5,380
  • 5
  • 41
  • 97
  • 1
    Yes, this is poor-man's "index into a type parameter pack". Which is somewhat silly in this case because you might as well just write the function as taking `T&&, Ts&&...` and use `T` directly. – T.C. Apr 25 '16 at 02:44

1 Answers1

1

No, the typename keyword, for all practical purposes, means the same thing as class.

The difference is slightly semantic. In the context of a template function or a class, a typename can also be a POD, rather than a formally declared class. It literally means "any type, a POD or a class", loosely speaking.

That's what the keyword typename means in generally. In this case, this has a specific purpose:

typename std::tuple_element<0, std::tuple<Ts...> >::type

This tells the compiler to expect the "type" in a std::tuple_element<0, std::tuple<Ts...> > is also going to be class (or a typedef), as opposed to a class member.

When you have something that looks like:

classname::identifier

This can refer to either a type or a class member:

class X {

public:
     typedef int y;
     int z;
};

Here, X::y refers to a type, and X::z refers to a class member. When it comes to parsing templates, a C++ compiler will assume by default that "A::b" is going to refer to a class member, unless you stick a typename in front of it, in which case it'll get parsed as a type.

Sam Varshavchik
  • 84,126
  • 5
  • 57
  • 106
  • 1
    Hey Sam. Few thoughts: `typename` and `class` can be used interchangeably when listing template parameters a la `template `. *"a `typename` can also be a POD, rather than a formally declared class."* - this is equally true of `A` and `B` in my earlier example - the compiler doesn't differentiate, though some coding standards do. *"as opposed to a class member"* / *"going to refer to a class member"*- types/`typedef`s can be class members - it would be better to contrast them with class *data* member. – Tony Delroy Apr 25 '16 at 02:52