Linux C ++:如何正确使用跨多个文件的模板专门化? [英] Linux C++: How to properly use template specializations across multiple files?

查看:160
本文介绍了Linux C ++:如何正确使用跨多个文件的模板专门化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的问题。在Windows上,使用Visual Studio 2010和英特尔编译器,一切都按预期链接。但是当我试图在Linux上编译我的代码与CLang 3.0,它会编译(如果我只使用一个CPP文件,它也链接和运行),但不链接。



消息是有多个符号定义,引用模板方法。例如,考虑在跨多个编译单元共享的头文件中的以下两行:

  template< class T& void myFunc(T in){} 
template<> void myFunc< int>(int in){}



现在从Linux链接器行的:


文件xyz:myFunc(int in)的多重定义,首先在某个文件中定义。


但我该如何防止呢?因为它在Windows上工作我认为它应该在Linux上工作不知何故?



静态模板数据成员也是这样,与上面的一样,只是声明一个变量而不是一个函数。我宁愿如果它工作的静态模板数据成员。



如果一切都失败,我想我仍然可以创建一个MakeAll.cpp文件,只包括所有的CPP,但这听起来不是一个理想的解决方案给我...



感谢您的帮助!

解决方案

在我的理解,你实际上多次定义你的模板专业化,这也应该给你一个错误Windows编译器。



在你的头文件中,你一个函数:

 模板< void myFunc< int>(int in){} 

此定义将存在于多个编译单元中,



与普通非模板函数相同的规则适用于您的模板专用化:使用 inline 或使用单独的声明和定义,方法是将

  void myFunc< int>(int in); 



  template<> void myFunc< int>(int in)
{
// ...
}

.cpp 文件中。


I have a strange problem. On Windows, with Visual Studio 2010 and also with the Intel Compiler everything is linked as expected. But when I try to compile my code with CLang 3.0 on Linux, it does compile (and if I only use a single CPP file it does also link and run) but does not link.

The message is that there are multiple symbol definitions, referring to template instanciations. For example consider the following two lines in a header file shared across multiple compilation units:

 template<class T> void myFunc(T in) { }
 template<> void myFunc<int>(int in) { }

Now from the Linux linker I would get something along the lines of:

"file xyz": Multiple definition of "myFunc(int in)", first defined in "some file".

But how would I prevent that? Since it works on Windows I suppose it should work on Linux too somehow?

The same goes for static template data members, which are more or less the same as above just that you declare a variable instead of a function. I would prefer if it worked for static template data members.

If everything else fails I suppose I could still create a "MakeAll.cpp" file which just includes all CPP there are, but that doesn't sound like a desirable solution to me...

Thanks for your help!

解决方案

In my understanding, you are in fact defining your template specializations multiple times, and this should also give you an error for Windows compilers.

In your header file you are defining a function by providing a body:

template<> void myFunc<int>(int in) { }

This definition will exist in multiple compilation units and the linker should complain.

The same rules apply for your template specialization as for ordinary non-template functions: Either use inline or use a separate declaration and definition, by putting

template<> void myFunc<int>(int in);

in a header and

template<> void myFunc<int>(int in)
{
    // ...
}

in a .cpp file.

这篇关于Linux C ++:如何正确使用跨多个文件的模板专门化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆