隐式模板方法实例
我有一个包含带有非类型模板参数的模板方法的类。代码大小变得非常大,因此我尝试通过将其放入 .cpp 文件来避免内联。但我只能设法为每个非类型参数显式实例化它。
隐式实例化可能吗?它会是什么样子?在其他相关问题中,此链接 http://www.parashift.com/c++-提供了 faq-lite/templates.html ,但我找不到隐式实例化的解决方案(如果有类似的东西)...
class Example
{
public:
template<enumExample T_ENUM> void Foo(void);
};
使用它时,我收到 Foo (未解析的外部符号)的链接器错误。
I have a class containing a template method with a non-type template parameter. The code size got really big, so I tried avoiding the inlining by putting it into the .cpp file. But I can only manage to instantiate it explictly for each non-type parameter.
Is an implicit instantiation possible? What would it look like? In an other related question this link http://www.parashift.com/c++-faq-lite/templates.html is provided but I can't find a solution for implicit instantiation (if there is something like this)...
class Example
{
public:
template<enumExample T_ENUM> void Foo(void);
};
I get linker errors for Foo (unresolved external symbol) when using it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的问题是模板代码需要在实例化时可见。请参阅 C++ FAQ 35.13
这基本上意味着你不能做你想做的事。有一个导出关键字可以实现这一点,但它的支持很差,我相信已经从 C++0x 的标准中删除了。有关详细信息,请参阅 C++ 常见问题解答 35.14。
Your problem is that the template code needs to be visible at the point at which it is instantiated. See C++ FAQ 35.13
Which basically means you can't do what you are trying to. There is an export keyword that makes this possible, but it is very poorly supported and I believe has been removed from the standard in C++0x. See C++ FAQ 35.14 for more information.
对于隐式实例化,编译器需要查看函数模板的实现。通常这意味着实现需要位于头文件中。如果您只是想避免内联,您可以尝试在标头中编写函数模板的实现,但在类声明之外(尽管我不确定内联是您真正的问题)。
For implicit instantiation, the compiler needs to see the implementation of the function template. Usually this means that the implementation needs to be in a header file. If you just want to avoid inlining, you could try writing the implementation of the function template in the header, but outside of the class declaration (although I'm not sure inlining is your real problem).
要减少代码大小,您可以在适当的时候尝试通过实施 pimpl 惯用法 来减少依赖性。
To reduce code size you can try to reduce the dependencies by implementing, when appropriate, the pimpl idiom.