C ++模板构造函数,为什么要调用拷贝构造函数? [英] C++ Template constructor, why is copy constructor being called?

查看:92
本文介绍了C ++模板构造函数,为什么要调用拷贝构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有模板构造函数的类,并且代码实际上是在default-constructor之后调用 copy 构造函数,这对我来说没有意义,因为类型不正确.

例如:

  A类{上市:避免);//默认构造函数A(const A& other);//复制构造函数template< class TYPE>A(const TYPE& object_to_ref);//模板构造函数}; 

此模板构造函数 可以工作 (在其他情况下可以正确调用),但不能从另一个模板函数正确识别为正确"的构造函数:

  template< class TYPE>A&CreateA(const TYPE& object_to_ref){//此功能永远不会用"A"来指定,只用"B"来表示!!返回* new A(object_to_ref);//呼叫"A :: A(const A&)" !! ??} 

示例失败:

  B my_b;A&my_a = CreateA(my_b);//调用了"A :: A(const A&)",而不是"A :: A(const B&)"! 

这对我来说没有意义.类型与副本构造函数相匹配是错误的.发生了什么?(MSVC2008)

我的解决方法是在这种情况下不使用模板构造函数:

  template< class TYPE>A&CreateA(const TYPE& object_to_ref){A * new_a =新的A();//默认构造函数new_a-> setObjectToRef(object_to_ref);//其他模板成员功能返回* new_a;} 

问题:为什么在这种情况下未调用模板构造函数?

(变通方法似乎工作正常,您是否建议使用替代方法?)

编辑: B 不相关,在 B 和/或 A 之间未指定任何转换:

  B类{}; 

解决方案

您没有提供 B 的定义,因此我假设 A B 的祖先和 B 可以隐式转换为 A .在这种情况下,不会实例化 B 的模板,因为已经有一个非常合适的调用.

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.

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)

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:

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. In this case your template for B is not being instantiated, because there is a perfectly suitable call already.

这篇关于C ++模板构造函数,为什么要调用拷贝构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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