Search code examples
c++templatesg++codeblocksreturn-type

C++ size_type does not name a type


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


Solution

  • 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();