Hello, I have a problem with a header I'm trying to make. In Main.cpp, I have this function to store the combinations of the elements of vector S:

template <class T> vector<vector<T> > combinations(vector<T> S, ll k)
{
	vector<vector<ll> > combs = ncombinations(S.size(), k);
	vector<vector<T> > setcomb(combs.size(), vector<T>());
	for(unsigned int i=0; i<combs.size(); i++)
	{
		for(unsigned int j=0; j<combs[i].size(); j++)
		{
			setcomb[i].push_back(S[combs[i][j]]);
		}
	}
	return setcomb;
}

It works fine when it's inside Main.cpp, but when I try to put it inside a header "comb.h", I get an error. The header is like this:

comb.h

#define COMB_H_

#include <vector>

#define ll long long
#define ull unsigned long long

using namespace std;


template <class T> vector<vector<T> > combinations(vector<T> , ll );


#endif /* COMB_H_ */

comb.cpp

#include "comb.h"

template <class T> vector<vector<T> > combinations(vector<T> S, ll k)
{
	vector<vector<ll> > combs = ncombinations(S.size(), k);
	vector<vector<T> > setcomb(combs.size(), vector<T>());
	for(unsigned int i=0; i<combs.size(); i++)
	{
		for(unsigned int j=0; j<combs[i].size(); j++)
		{
			setcomb[i].push_back(S[combs[i][j]]);
		}
	}
	return setcomb;
}

When I call cambinations() inside Main.cpp, I get this error:

referencia a `std::vector<std::vector<char, std::allocator<char> >, std::allocator<std::vector<char, std::allocator<char> > > > combinations<char>(std::vector<char, std::allocator<char> >, long long)' sin definir

(undefined reference)

Other funtions I've put inside the header file work fine, but none of them uses templates. I don't understand what am I doing wrong, can you help me please?

I got this from http://stackoverflow.com/questions/115703/storing-c-template-function-definitions-in-a-cpp-file

The problem you describe can be solved by defining the template in the header, or via the approach you describe above. I recommend reading points 35.12, 35.13, and 35.14 from the C++ FAQ Lite:
http://www.parashift.com/c++-faq-lite/templates.html

Thank you very much! That solved my problem, I'll take a better look at the C++ FAQ the next time.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.