Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Template: 'is not derived from type'

Why is this code not valid?

#include <vector>

template <typename T>
class A {
  public:
    A() { v.clear(); }

    std::vector<A<T> *>::const_iterator begin() {
      return v.begin();
    }

  private:
    std::vector<A<T> *> v;
};

GCC reports the following errors:

test.cpp:8: error: type 'std::vector<A<T>*, std::allocator<A<T>*> >' is not derived from type 'A<T>'
test.cpp:8: error: expected ';' before 'begin'
test.cpp:12: error: expected `;' before 'private'

What is wrong? How to fix it?

like image 441
Allan Avatar asked May 15 '10 21:05

Allan


People also ask

What is a non-type template parameter?

A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument. A non-type parameter can be any of the following types: An integral type. An enumeration type. A pointer or reference to a class object.

How template works in C++?

While using a template in C++, you pass a data type as a parameter. Thus, instead of maintaining multiple codes, you have to write one code and give the data type you want to use. C++ templates use two primary keywords, 'template' and 'typename,' where the 'typename' can be replaced with the 'class' keyword.

What is a template parameter C++?

A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.

How to define template class in cpp?

Templates in C++ is an interesting feature that is used for generic programming and templates in c++ is defined as a blueprint or formula for creating a generic class or a function. Simply put, you can create a single function or single class to work with different data types using templates.


1 Answers

In this line, you are missing the typename keyword:

std::vector<A<T> *>::const_iterator begin(){

You need:

typename std::vector<A<T> *>::const_iterator begin(){

This because std::vector<A<T> *> is dependent on the template parameter (T) of the class template (A). To enable correct parsing of the template without having to make any assumptions about possible specializations of any other templates, the language rules require you to indicate which dependent names denote types by using the typename keyword.

like image 175
CB Bailey Avatar answered Sep 23 '22 17:09

CB Bailey