gpt4 book ai didi

c++ - 继承构造函数是否适用于 C++0x 中的模板?

转载 作者:IT老高 更新时间:2023-10-28 21:36:34 25 4
gpt4 key购买 nike

在 C++0x 中,您可以使用 using 关键字来继承构造函数,如下所示:

class B { B(int) {} };

class A : public B { using B::B; };

这将隐式声明一个 A(int) 构造函数。这适用于模板吗?

class B { B(int) {} };

template<class T> class A : public T { using T::T; };

T::T 中,我希望编译器能够找出左侧的 T,因为在模板参数上使用范围运算符是正常的,但要弄清楚右手 T 是构造函数是一个特例。事实上,它似乎有一个歧义:如果我在 B 中有一个名为 T 的方法,我试图在 A 中添加重载(这就是编译器在 C++0x 之前解释这种 using 声明的方式)?

最佳答案

是的,它有效,原因是名称查找机制。继承构造函数声明的工作机制很简单:如果 using 声明的名称指的是基类构造函数,那就是继承构造函数声明。在 3.4.3.1[class.qual]p2 我们发现:

In a lookup in which the constructor is an acceptable lookup result and the nested-name-specifier nominates a class C

  • if the name specified after the nested-name-specifier, when looked up in C, is the injected-class-name of C (Clause 9), or
  • in a using-declaration (7.3.3) that is a member-declaration, if the name specified after the nested-name-specifier is the same as the identifier or the simple-template-id's template-name in the last component of the nested-name-specifier

the name is instead considered to name the constructor of class C.

这是使类构造函数定义起作用的段落,也是使继承构造函数声明起作用的段落。第二个项目符号适用于这种情况:

struct B {
B(int) { }
};

typedef B mytype;

struct A : B {
// "name ... is the same as the identifier ... in the last component ..."
using mytype::mytype;
};


template<typename T> using same = T;

struct C : B {
// "name ... is the same as the template-name ... in the last component ..."
same<B>::same;
};

后一个例子证明在以下情况下也很有用

template<template<typename> class Base>
struct X : Base<int> {
using Base<int>::Base;
};

总结:

  • 上面的第一个项目符号是语义规则 - 如果嵌套名称说明符后面的名称是指注入(inject)的类名称(B::Bmytype::B),那么它将被翻译为引用构造函数。

  • 第二个项目符号是句法规则 - 名称必须匹配 - 否则它们的含义无关紧要 - 在提供给 的模板参数中可能有一个名为 Base 的成员X,如下所示,但 using 声明仍会导入构造函数,并且将成员命名为Base:

    template<typename T> struct D { private: T Base; };
    X<D> x; // valid, the private member is *not* touched!

关于c++ - 继承构造函数是否适用于 C++0x 中的模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7394492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com