0

This is the code I am using:

#include <iostream> #include <vector> #include <algorithm> using namespace std; class Vector { // Use user defined template class for vector handling template <class V,class D> void vec_add(V &vec, D data) { vec.push_back(data); } }; int main () { vector<int> v; // v is vecor of int elements Vector.vec_add(&v,222); } 

Goal: Define a generic add of item to any kind of vector.
Problem: I am getting a compilation error.

3 Answers 3

1

There are many issues:

First, make the member functions public:

class Vector { public: 

Second,

Vector.vec_add(&v,222); 

should be something like

 Vector foo; foo.vec_add(v,222); 

as you are passing a reference, not a pointer, and you must invoke the member function on an instance, in this case foo, as the member function is not static (think whether you want to make it static, in which case you invoke it as Vector::vec_add). Full working code below:

#include <iostream> #include <vector> #include <algorithm> using namespace std; class Vector { public: // Use user defined template class for vector handling template <class V, class D> void vec_add(V &vec, D data) { vec.push_back(data); } }; int main () { vector<int> v; // v is vecor of int elements Vector foo; foo.vec_add(v, 222); std::cout << v.front(); // test it } 

Live on Coliru

A good advice is to pick up a book from here and learn the basic features of the language.

Sign up to request clarification or add additional context in comments.

Comments

0

Why bother making a class? It would have to be static member function, because you didn't make any Vector objects. Better use normal functions, if you don't have any plans with the class alone:

#include <iostream> #include <vector> #include <algorithm> using namespace std; template <class V,class D> void vec_add(V &vec, D data) { vec.push_back(data); } int main () { vector<int> v; // v is vecor of int elements vec_add(v,222); } 

1 Comment

Maybe suggest namespace
0

You have a several problems with your code: your vec_add is private, it is non static, also you call it with pointer to std::vector - while your method accepts a reference. Below is an example with fixed errors, hopefully this is what you want:

#include <iostream> #include <vector> #include <algorithm> using namespace std; class Vector { // Use user defined template class for vector handling public: template <class V,class D> static void vec_add(V &vec, D data) { vec.push_back(data); } }; int main () { vector<int> v; // v is vecor of int elements Vector::vec_add(v,222); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.