0

How do I explicitly instantiate a Template with integer parameter

Example :

foo.h

template<int DIM>
class foo{
public: 
    foo();
};

foo.cpp

#include "foo.h"
template<int DIM>
foo<DIM>::foo(){
    return;
}

main.cpp

#include "foo.h"
int main(){
    foo<1> obj;
    return 0;
}

Here, I get a main.cpp: undefined reference to `foo<1>::foo()'

Typically we use a template class foo in the cpp file. How do we do this in this case.

thanks

EDIT : Solution Similar to the template class foo, we just need to add

template class foo<1>;

Some_Guy
  • 169
  • 11
  • This has nothing to do with integer parameters, but with how templates work in C++. Your compiler must know the template's definition, and it can't possibly know that when it's only compiling `main.cpp`. Put the template definition into the header file, see the linked question for more information. – Sam Varshavchik May 01 '22 at 13:33
  • @SamVarshavchik Here unlike the traditional where we can specify possible definitions, here it is a integer value... How do I do this.... The "putting it in the header file solution works"... I just wanted to know how to do explicit instantiation in the cpp file – Some_Guy May 01 '22 at 13:35
  • 1
    @Some_Guy It's exactly the same. `template class foo<1>;` – Yksisarvinen May 01 '22 at 13:36
  • This has nothing to do with "here it is an integer value". How do you expect your C++ compiler to possibly know that the template function contains a single `return` statement, instead of the source code to the entire control system for a Boeing 777, when it's only compiling `main.cpp`? – Sam Varshavchik May 01 '22 at 13:37
  • @Yksisarvinen This works.. Some how I did not try this.. Thanks. – Some_Guy May 01 '22 at 13:39
  • 1
    Here's a working example as well: https://godbolt.org/z/1M9Kod7jz (man, I really don't understand Godbolt...) – Yksisarvinen May 01 '22 at 13:45

0 Answers0