gpt4 book ai didi

模板化继承类中的 C++ 成员变量初始化

转载 作者:行者123 更新时间:2023-11-28 05:33:25 33 4
gpt4 key购买 nike

我想弄清楚这段代码有什么问题。基本上 type2继承自 type1<T>, type1<T2>我想初始化 value来自基类之一的成员。

#include <utility>

template <typename T>
struct type1 {
using base_type = T;

template <typename... Args> type1(Args&&... args) : value(std::forward<Args>(args)...) {}

T value;
};

template <typename... Ts>
struct type2 : public Ts... {
template <typename T>
type2(T&& arg) : T::value(std::move(arg.value)) {}
};

int main()
{
type2<type1<int>, type1<double>> x(type1<int>(10));
return 0;
}

但是我从 clang 得到以下错误:

    Error(s):

source_file.cpp:15:25: error: typename specifier refers to non-type member 'value' in 'type1<int>'
type2(T&& arg) : T::value(std::move(arg.value)) {}
^~~~~
source_file.cpp:20:38: note: in instantiation of function template specialization 'type2<type1<int>, type1<double> >::type2<type1<int> >' requested here
type2<type1<int>, type1<double>> x(type1<int>(10));
^
source_file.cpp:9:7: note: referenced member 'value' is declared here
T value;
^
1 error generated.

为什么 clang 说 typename specifier refers to non-type member 'value' in 'type1<int>' ? Gcc 想要处理(可能也是 clang)value作为一种类型:

Error(s):

source_file.cpp: In instantiation of ‘type2<Ts>::type2(T&&) [with T = type1<int>; Ts = {type1<int>, type1<double>}]’:
source_file.cpp:20:54: required from here
source_file.cpp:15:51: error: no type named ‘value’ in ‘struct type1<int>’
type2(T&& arg) : T::value(std::move(arg.value)) {}
^

最佳答案

您不能在构造函数初始化列表中初始化基类的成员。

在标准语中,T::value(std::move(arg.value))type2(T&& arg) 中:T::value(std::move(arg. value)) {} 称为 mem-initializerT::value 称为 mem-initializer-id .根据[class.base.init]p2 ,

Unless the mem-initializer-id names the constructor's class, a non-static data member of the constructor's class, or a direct or virtual base of that class, the mem-initializer is ill-formed.

可以调用基类的构造函数,让它初始化成员。在这种特定情况下,您只需将 T::value(std::move(arg.value)) 更改为 T(std::move(arg.value))Demo .

关于模板化继承类中的 C++ 成员变量初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38886035/

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