继承自作为模板参数传递的const类型

问题描述 投票:22回答:1

以下代码无效:

struct base {
};

struct inherit : const base {
};

你不能继承const类型。

涉及模板时情况是否会发生变化?换句话说,这段代码是否有效:

struct base {
};

template<typename T>
struct inherit : T {
    using T::T;
};

int main() {
    inherit<base const>{};
}

gcc说这很好,但clang报道

<source>:6:2: error: 'const base' is not a direct base of 'inherit<const base>', cannot inherit constructors

        using T::T;

        ^        ~

<source>:10:2: note: in instantiation of template class 'inherit<const base>' requested here

        inherit<base const>{};

        ^

1 error generated.

Compiler returned: 1

为了让clang高兴,我需要做这样的事情:

template<typename T>
struct inherit : T {
    using U = std::remove_const_t<T>;
    using U::U;
};

哪个版本是正确的?或者他们都不正确我需要继承std::remove_const_t<T>

c++ c++11 c++14 language-lawyer
1个回答
16
投票

感谢@T.C.我们有:

[temp.param]/3说:

标识符不遵循省略号的类型参数将其标识符定义为typedef-name(如果使用classtypename声明)...在模板声明的范围内。

所以它就像typedef一样工作。

然后[class.name]/5

如果在需要类名的地方使用命名cv限定类类型的typedef-name,则忽略cv限定符。

因此GCC是正确的,const应该在继承T时被剥离,因为类名需要at that point,以及using T::T;继承构造函数声明。

© www.soinside.com 2019 - 2024. All rights reserved.