模板类专业化依赖于构造函数参数?
我正在调查 C++ 类模板的问题。一个类模板是专门化的,但编译器并不总是选择使用专门化。我发现构造函数参数似乎会影响这一点:
temlate <class T>
class MyClass { /*some constructors*/ };
template<>
class MyClass <int>
{ void foo(); /*some constructors*/}
MyClass<int> test1;
test1.foo(); //works
MyClass<int> test1("hallo");
test1.foo(); //doesn't work (foo does not exist, compiler uses unspecialized version.)
我还没有设法创建一个显示问题的示例,因为构造函数参数非常复杂(并且简单参数不会出现问题)。
但我的问题很简单:构造函数参数是否有可能影响编译器的选择?如何?
我正在使用 Visual C++ 2008。
非常感谢!
---- 编辑:
看来我们已经发现了问题:如果模板专业化不是我们构建的静态库中所有翻译单元的一部分,则会出现问题。但如果没有其他翻译单元,它就会消失。
我发现 http://codeidol.com/cpp/cpp-templates/Instantiation/实现方案/ 在我看来,通过贪婪实现,我们观察到的现象可以得到解释。
有谁知道MSVC和GCC实际上使用了哪些实现方案?
I am investigating a problem with C++ class templates. One class template is specialized but the compiler does not always choose to use the specialization. I found that the constructor arguments seem to influence this:
temlate <class T>
class MyClass { /*some constructors*/ };
template<>
class MyClass <int>
{ void foo(); /*some constructors*/}
MyClass<int> test1;
test1.foo(); //works
MyClass<int> test1("hallo");
test1.foo(); //doesn't work (foo does not exist, compiler uses unspecialized version.)
I haven't managed to create a sample that shows the problem because the constructor arguments are pretty complex (and the problem does not occur with simple arguments).
But my question is simply this: Is it possible, that constructor arguments influence the choice of the compiler? How?
I am working with Visual C++ 2008.
Thanks a lot!
---- EDIT:
It seems like we have identified the problem: If the template specialization was not part of all the translation units in the static library that we build, the problem occurs. But it disappears, if there are no other translation units.
I found http://codeidol.com/cpp/cpp-templates/Instantiation/Implementation-Schemes/ and it seems to me that with the Greedy Implementation the phenomena we observed can be explained.
Does anybody know which implementation schemes are actually used by MSVC and GCC?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,因为你告诉它你想使用哪种类型:
总是创建专门类型的对象。
No, because you are telling it which type you want to use :
is always creating objects of the specialized type.
全局模板函数将是一种类型,编译器将使用函数参数进行类型推导。类似地,类模板的“类型”参数将用作类的模板参数。
但是您想要一个构造函数(它是某些类型的部分)参与模板类型推导 - 这是不可能的。
A global template function would be a type, and compiler would use the function arguments for type deduction. Similarly, the "type" arguments for class template would be used as template arguments for class.
But you want a constructor (which is part of some type), to be participated in the template-type deduction - which is not possible.