user3879626
user3879626

Reputation: 127

Template of vector in C++ compilation error

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.

Upvotes: 0

Views: 96

Answers (3)

marcinj
marcinj

Reputation: 49986

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);
}

Upvotes: 0

vsoftco
vsoftco

Reputation: 56557

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.

Upvotes: 1

xinaiz
xinaiz

Reputation: 7788

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);
}

Upvotes: 0

Related Questions