Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 调用继承参数包的模板构造函数_C++_Templates_Inheritance_Constructor_C++17 - Fatal编程技术网

C++ 调用继承参数包的模板构造函数

C++ 调用继承参数包的模板构造函数,c++,templates,inheritance,constructor,c++17,C++,Templates,Inheritance,Constructor,C++17,下面的代码可能有两个相关的问题 它只是分别定义了两种类型Type1和Type2,以及从这两种类型继承的“聚合”类型types 我的最终目标是使注释的构造函数工作,以避免临时变量初始化。如果我在Types下取消注释代码,编译器会给出一个错误: error: class ‘Types<Args>’ does not have any field named ‘Args’ 实际输出为 Type1:1 Type2:0 Type1:0 Type2:0 我不知道我的两个问题是否相互关联。

下面的代码可能有两个相关的问题

它只是分别定义了两种类型
Type1
Type2
,以及从这两种类型继承的“聚合”类型
types

我的最终目标是使注释的构造函数工作,以避免临时变量初始化。如果我在
Types
下取消注释代码,编译器会给出一个错误:

error: class ‘Types<Args>’ does not have any field named ‘Args’
实际输出为

Type1:1
Type2:0
Type1:0
Type2:0
我不知道我的两个问题是否相互关联。 我猜这两个问题都是由于我可能不了解参数包和继承,因此我将发布这两个问题

如果有人能解释这两个问题,我将不胜感激

结构类型1{
Type1()=默认值;
模板
Type1():init_{std::is_same::value}{};
模板
Type1(tt):init{std::is_same::value}{

void Print()const{std::cout似乎自动生成并使用复制构造函数而不是模板函数。我明确添加了复制构造函数:

  template <typename T>
  Type1(T t) {}
  Type1(const Type1& t) : init_{true} {}
模板
类型1(T T){}
Type1(consttype1&t):init{true}{}
这两种类型似乎都有效

另一个注意事项是将打印行切换到:

  static_cast<Type1&>(types).Print();
  static_cast<Type2&>(types).Print();
static_cast(类型).Print();
静态转换(类型).Print();

因为如果您只是对非引用类型进行
static\u强制转换
,则会生成副本(如果它是已定义的行为)。

从顶部开始:
template Type1()
永远不能使用,因为调用构造函数时没有语法提供显式的模板参数,也没有参数可以从中推断出来。
static\u cast(types)
创建一个类型为
Type1
的临时构造函数,使用带有
types
的模板构造函数作为其参数。它相当于
Type1{types}
。当然,
types
的类型不是
Type1
。您正在调用
Print()
在那个临时的,而不是在
类型中的
类型1
子对象上
@IgorTandetnik非常感谢你帮我解决这个问题。我更新了原始帖子,包含了原始代码中存在的所有问题。我认为与之前的评论一起,完全解决了这个问题。我更新了我的原始帖子,并标记了你的答案已接受。非常感谢您抽出时间!
  static_cast<Type1&>(types).Print();
  static_cast<Type2&>(types).Print();