初始化忽略构造函数模板 [英] initialization ignores constructor templates

查看:155
本文介绍了初始化忽略构造函数模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在追求一些错误时,我偶然发现了下面的初始化行为,这对我来说很奇怪:在初始化检查现有的构造函数时,似乎有些情况下会忽略适配构造函数的模板。例如考虑以下程序:

While pursuing some errors, I stumbled upon the following behavior of initialization, which seems odd to me: While initialization checks for existing constructors, there seem to be cases were templates for fitting constructors are ignored. Consider for example the following program:

#include <iostream>

template<class T>
struct A {
 A() {};
 template<class S>
 A(const A<S>& a) {std::cout << "constructor template used for A" << std::endl;};
};

template<class T>
struct B{
 B() {};
 B(const B<int>& b) {std::cout << "constructor used for B" << std::endl;};
};

int main() {
 A<int> a;
 B<int> b;
 A<int> aa = a;
 B<int> bb = b;
 A<double> aaa = a;
}

对我来说,这产生输出

constructor used for B
constructor template used for A

这意味着它不使用main的第三行中的构造函数。为什么不?有理由吗?还是我的语法在某处?模板似乎工作,因为它在最后一行成功使用。

this means it does not use the constructor in the third line of main. Why not? Is there a reason? Or is my syntax off somewhere? The template seems to work, as it is successfully used in the last line.

我知道这个例子似乎过于复杂,但各种简化使我想显示的行为远。另外:模板专业化将由初始化使用,并且是我目前防止这种情况导致错误(它首先导致错误)。

I know the example seems overly complicated, but various simplifications made the behavior I wanted to display go away. Also: A template specialization will be used by the initialization and is how I currently prevent this causing errors (where it caused errors in the first place).

对不起if我的问题是以任何方式关闭,我不是一个程序员,我不是一个母语,这是我的第一个问题,请原谅我。

I am sorry if my question is off in any way, I am not a programmer, I am not a native speaker and this is my first question, please forgive me.

推荐答案

编译器提供了一个隐式声明的非模板拷贝构造函数,其签名等同于

The compiler provides an implicitly declared non-template copy constructor with signature equivalent to

A(const A& a);

因为模板构造函数不被视为用户定义的复制构造函数,即复制构造函数必须是非模板。

because a template constructor is not considered as a user defined copy constructor, i.e. a copy constructor has to be a non-template.

隐式声明的复制构造函数在重载分辨率上比模板版本更好地匹配,当从 A< T> 中复制构造 A< T> 这可以用一个简单的例子来说明,用户定义 A(const A&)

The implicitly declared copy constructor is a better match in the overload resolution than the template version, and is the one that gets called when you copy construct an A<T> from an A<T>. This can be illustrated with a simple example, with a user defined A(const A&):

#include <iostream>

template<class T>
struct A 
{
 A() {};

 A(const A& a) {
   std::cout << "copy constructor used for A" << std::endl;
 }

 template<class S>
 A(const A<S>& a) {
   std::cout << "constructor template used for A" << std::endl;
 }
};

int main()
{
  A<int> ai;
  A<double> ad = ai; /  calls template conversion contructor
  A<int> ai2 = ai;   // calls copy constructor A(const A&);
}

这篇关于初始化忽略构造函数模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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