Explicit template instantiation in shared libraries

Now a little bit of C++ stuff. Usually I consider this language a bit undercooked, in its "advanced" features, like templates, but sometimes they could be useful. Consider following simple example:
a.hpp:
class C {
public:
 template <class T> void run(T x);
};
a.cpp:
#include "a.hpp"
#include <stdio.h>

template <class T> void C::run(T x) {
  if (x > 0) {
    printf("positive\\n");
  }
}

// Note this!
template void C::run<int>(int x);

b.cpp:
#include "a.hpp"
void foo() {
  C().run(3);
}
If we link those files with g++ -fPIC -shared a.cpp b.cpp -o liba.so unless explicit template instantiation line included, this library will fail to load, due to unresolved symbols.
Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
About

nike

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today