简体   繁体   English

C ++模板构造函数,为什么要调用拷贝构造函数?

[英]C++ Template constructor, why is copy constructor being called?

I have a class with a template constructor, and the code is actually calling the copy constructor, after the default-constructor, which does not make sense to me as the type is incorrect. 我有一个带有模板构造函数的类,并且代码实际上是在default-constructor之后调用副本构造函数,这对我来说没有意义,因为类型不正确。

For example: 例如:

class A
{
  public:
    A(void); // default constructor
    A(const A& other); // copy constructor
    template<class TYPE>
    A(const TYPE& object_to_ref);  // template constructor
};

This template constructor works (is properly called in other cases), but is not properly recognized as the "correct" constructor from another template function: 此模板构造函数可以工作 (在其他情况下可以正确调用),但不能从另一个模板函数正确识别为“正确”的构造函数:

template<class TYPE>
A& CreateA(const TYPE& object_to_ref)
{
  // THIS FUNCTION IS NEVER SPECIALIZED WITH "A", ONLY WITH "B" !!
  return *new A(object_to_ref);  // CALLS "A::A(const A&)" !!??
}

Example fail: 示例失败:

B my_b;
A& my_a = CreateA(my_b);  // "A::A(const A&)" called, not "A::A(const B&)"!

This does not make sense to me. 这对我来说没有意义。 The types are wrong to match the copy constructor. 类型与副本构造函数匹配错误。 What happened? 发生了什么? (MSVC2008) (MSVC2008)

My work-around is to not use the template constructor in this case: 我的解决方法是在这种情况下不使用模板构造函数:

template<class TYPE>
A& CreateA(const TYPE& object_to_ref)
{
  A* new_a = new A(); //DEFAULT CONSTRUCTOR
  new_a->setObjectToRef(object_to_ref); //OTHER TEMPLATE MEMBER FUNCTION
  return *new_a;
}

QUESTION: Why was the template constructor not called in this case? 问题:为什么在这种情况下不调用模板构造函数?

(Work-around seems to behave properly, do you suggest an alternative?) (变通方法似乎工作正常,您是否建议替代方法?)

EDIT: B is unrelated, with no conversions specified between B and/or A : 编辑: B是无关的,没有在B和/或A之间指定任何转换:

class B
{
};

You didn't provide definition of B , so I'm going ahead assuming that A is B 's ancestor and B can be implicitly cast to A . 您没有提供B定义,因此我假设AB的祖先,并且B可以隐式转换为A In this case your template for B is not being instantiated, because there is a perfectly suitable call already. 在这种情况下,您的B模板不会被实例化,因为已经有一个非常合适的调用。

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

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