简体   繁体   English

模板类专业化取决于构造函数参数吗?

[英]Template class specialization dependent on constructor arguments?

I am investigating a problem with C++ class templates. 我正在研究C ++类模板的问题。 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. 我正在使用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. 我发现http://codeidol.com/cpp/cpp-templates/Instantiation/Implementation-Schemes/ ,在我看来,通过贪婪的实现,可以解释我们观察到的现象。

Does anybody know which implementation schemes are actually used by MSVC and GCC? 有人知道MSVC和GCC实际使用了哪些实现方案吗?

But my question is simply this: Is it possible, that constructor arguments influence the choice of the compiler? 但是我的问题很简单:构造函数参数可能会影响编译器的选择吗? How? 怎么样?

No, because you are telling it which type you want to use : 不,因为您正在告诉它要使用哪种类型:

MyClass<int> test1; 
test1.foo(); //works

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. 但是您希望构造函数( 属于某种类型的 一部分 )参与模板类型的推导-这是不可能的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM