Help In code template
Given this code
template <typename T>
typename T::ElementT at (T const &a , T const &b)
{
return a[i] ;
}
what do
ty开发者_运维问答pename T::ElementT
and
a[i]
mean?
typename T::ElementT
Since T:ElementT
is a dependent name, that is why you see the keyword typename
before it. It tells the compiler that ElementT
is a tested type, not value.
And as for a[i]
, it seems that T
is a class that has defined operator[]
which is being called when you write a[i]
. For example, T
could be sample
as (partially) defined here:
class sample
{
public:
typedef int ElementT; //nested type!
//...
ElementT operator[](int i)
{
return m_data[i];
}
ElementT *m_data;
//...
};
Now, if T
is sample
, then you can write T::ElementT
as well as a[i]
which is of type T
. In this case when T
is sample, I'm assuming that the type of index i
is int
.
i guess in that code T is always a class which has operator [] overloaded and has a subclass defenition ElementT any other class which doesn't have these two qualities will make an error while compile.
typename T::ElementT
This is explained exhaustingly by Johannes in this entry to the C++ FAQ.
a[i]
This operation is usually called "subscription" and accesses the i-th element in a
. In order to do that, a
must either be an array or some class that overloads the subscription operator (like std::vector
or std::map
).
However, as Nawaz pointed out in his comment, since a
is of type T
, and since T
is expected to have a nested type ElementAt
, in this case a
cannot be an array.
精彩评论