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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With