Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using non-exporting functions inside templates in C++ modules

Tags:

c++

visual-c++

Consider the following module:

module M;

// a private, non-exporting function
int id(int x) {
    return x;
}

export
template <class T>
int f(T x) {
    return id(0);
}

export
int g(int y) {
    return id(1);
}

And the following C++ code using it:

import M;

int main() { 
    g(42);
    return 0; 
}

It successfully compiles with VS2015 update 1 and works, but if I replace g with f, the compiler complains: error C3861: 'id': identifier not found.

How to fix it?

like image 335
Ignat Loskutov Avatar asked Mar 03 '16 12:03

Ignat Loskutov


1 Answers

You face this problem because of templates instantiation rules. For the same reason as you include templates definition in C++ header files (and don't define them in separate .cpp files), you can't export template function from module in this way.

It's not a good practice to export template functions or classes from module because you should have all instantiations, that will probably be used, within this module. However if you want to implement it in this way for some reason, you should instantiate function f() with T as int in the module, e.g. add useless call with integer argument within this module.

like image 101
CodeFuller Avatar answered Oct 15 '22 20:10

CodeFuller