-2

While trying to create a function to calculate the length of a vector, I encountered error: 'size_type' does not name a type for line 2. Is size_type not already a type? What exactly does it mean to name a type?

template<class vecType>
size_type len(vector<vecType> inVector) {
    size_type vecSize = inVector.size();
    return vecSize;
}

FYI : Using gcc/g++ 4.9.2

user3576467
  • 354
  • 4
  • 10
  • 2
    "name" is a verb in this case. It means `size_type` is not a name of a data type. It means you have not told the compiler what `size_type` is. –  Mar 17 '17 at 02:01
  • `size_type` is usually attached to another class, such as `vector::size_type` – user4581301 Mar 17 '17 at 02:02
  • Related: http://stackoverflow.com/questions/4849632/vectorintsize-type-in-c – user4581301 Mar 17 '17 at 02:04

2 Answers2

2

Let's take a look at a regular function, not a function template.

int add_two(int in)
{
   return (in + 2);
}

The int before the name of the function is the return type. If the compiler cannot determine that it represents a type, it will report that as an error. If you had a typo and wrote

imt add_two(int in)
{
   return (in + 2);
}

the compiler will complain that imt is not a type.

A function template must also have a return type. You have:

template<class vecType>
size_type len(vector<vecType> inVector) {
    size_type vecSize = inVector.size();
    return vecSize;
}

Here, you have size_type before the function name. If the compiler cannot determine that size_type is indeed a type, it will complain. If size_type is a known type, the compiler will proceeds with that type being the return type of the function.

You can use:

template<class vecType>
typename std::vector<vecType>::size_type len(vector<vecType> inVector) {
   ...
}

to let the compiler know that std::vector<vecType> has a type called size_type and the return value of that function is that type. You will need to use typename std::vector<vecType>::size_type since it is a dependent type name. See Where and why do I have to put the "template" and "typename" keywords? for more on the subject.

Also, you have to fix the declaration of the variable vecSize in the function.

template<class vecType>
typename std::vector<vecType>::size_type len(vector<vecType> inVector) {
   typename std::vector<vecType>::size_type vecSize = inVector.size();
   return vecSize;
}

If you are able to use a C++11 compiler, you can simplify the variable declaration to

   auto vecSize = inVector.size();
Community
  • 1
  • 1
R Sahu
  • 196,807
  • 13
  • 136
  • 247
-1

Try

vector<vecType>::size_type vecSize = inVector.size ();
user481779
  • 1,031
  • 1
  • 12
  • 26