C++ template static method

Apr 5, 2014 at 9:07am
I found a useful method on the internet but I want to use it as a static method. The problem is it contains a template type and I don't know how to make it work.
I tried it like this:

Tools.h
1
2
3
4
5
6
class Tools
{
public:
	template <typename T>
	static T **allocateDynamicArray( int nRows, int nCols);
};


Tools.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
#include "Tools.h"

template <typename T> 
T **Tools::allocateDynamicArray( int nRows, int nCols)
{
      T **dynamicArray;

      dynamicArray = new T*[nRows];
      for( int i = 0 ; i < nRows ; i++ )
      dynamicArray[i] = new T [nCols];

      return dynamicArray;
}


Building the code without calling the method works, but when trying to call it there's an error.

This doesn't work:
Tools::allocateDynamicArray<int>(1,1);

Am I making any mistakes? Or is it impossible to do this? I'm using Visual Studio 2012.
Apr 5, 2014 at 9:16am
Hello, Bingo90! Welcome to our community.
It's usually a good idea to include error message as well - it may help us find error in your code. Simply stating "it gives me an error" isn't much helpful.

Especially, that for me - this code works.
I think I know what your problem is.
When you make class with template methods, all template methods have to be defined in header file. You lose a bit of encapsulation, but if you move it, you'll have your method working.

And as a bit of advice, if your class doesn't do anything more - it may as well be replaced with namespace.

Cheers!
Last edited on Apr 5, 2014 at 9:16am
Apr 5, 2014 at 9:23am
The cpp and h files I posted are the same as the files in my project.
Apr 5, 2014 at 9:52am
It compiles fine in Code::Blocks
I can't think of anything wrong ?

I can't think of anything more adives than MatthewRock had said

--
Apr 5, 2014 at 10:31am
All templated code should be in header files. You are trying to compile template in separate cpp file, but compiler does not know which versions of function it should generate.
Apr 5, 2014 at 10:44am
Here's the error message:

Error 1 error LNK2019: unresolved external symbol "public: static int * * __cdecl Tools::allocateDynamicArray<int>(int,int)" (??$allocateDynamicArray@H@Tools@@SAPAPAHHH@Z) referenced in function _main C:\Users\Username\documents\visual studio 2012\Projects\Project\Project\main.obj
Apr 5, 2014 at 11:23am
As @MiiNiPaa suggested, move your code from Tools.cpp to Tools.h, otherwise the compiler can't generate the relevant functions from your template.
Apr 5, 2014 at 11:25am
Ah yes that worked, thank you all :D
Topic archived. No new replies allowed.