在c++模块的模板中使用非导出函数

时间:2022-04-02 23:29:28

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:

使用它的c++代码如下:

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.

它成功地编译了VS2015更新1和工作,但是如果我用f替换g,编译器会抱怨:错误C3861:“id”:没有找到标识符。

How to fix it?

如何修复它吗?

1 个解决方案

#1


3  

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.

您面临这个问题是因为模板实例化规则。与在c++头文件中包含模板定义(不要在单独的.cpp文件中定义它们)一样,您不能以这种方式从模块中导出模板函数。

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.

从模块中导出模板函数或类不是一个好的实践,因为您应该在这个模块中包含所有可能会用到的实例化。但是,如果您出于某种原因想以这种方式实现它,那么您应该在模块中实例化函数f(),其中T为int,例如,在这个模块中添加带有整型参数的无用调用。

#1


3  

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.

您面临这个问题是因为模板实例化规则。与在c++头文件中包含模板定义(不要在单独的.cpp文件中定义它们)一样,您不能以这种方式从模块中导出模板函数。

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.

从模块中导出模板函数或类不是一个好的实践,因为您应该在这个模块中包含所有可能会用到的实例化。但是,如果您出于某种原因想以这种方式实现它,那么您应该在模块中实例化函数f(),其中T为int,例如,在这个模块中添加带有整型参数的无用调用。