[英]Curiously recurring template pattern with variadic templates (C++)
I have the following piece of code: 我有以下代码:
#include <iostream>
template <typename Derived>
struct Base {
void print() const { static_cast<const Derived*>(this)->print(); }
};
struct Value : public Base<Value> {
int i;
void print() const { std::cout << "Value: " << i << std::endl; }
Value(int j) : i(j) {}
};
void do_variadic_thing() {}
template <typename Derived, typename... Args>
void do_variadic_thing(const Base<Derived>& b, Args... args) {
std::cout << "Inside do_variadic_thing" << std::endl;
b.print();
do_variadic_thing(args...);
}
template <typename Derived>
void do_thing(const Base<Derived>& b) {
std::cout << "Inside do_thing" << std::endl;
b.print();
do_variadic_thing(b, b, b);
}
int main(int argc, char** argv) {
do_thing(Value(1));
}
This code uses the Curiously Recurring Template Pattern define a compile-time polymorphic class with a method called print
. 该代码使用“好奇地重复使用的模板模式”,通过一个名为
print
的方法定义了一个编译时多态类。
What I want to do is to run the print
method from a function with a variable number of arguments ( do_variadic_thing
). 我想做的是从带有可变数量参数(
do_variadic_thing
)的函数中运行print
方法。 The code provided above compiles, but produces a strange output: 上面提供的代码可以编译,但是会产生奇怪的输出:
Inside do_thing
Value: 1
Inside do_variadic_thing
Value: 1
Inside do_variadic_thing
Value: 4206337
Inside do_variadic_thing
Value: 4206337
I do not understand why the value printed changes after the second recursive call within do_variadic_thing
. 我不明白为什么在
do_variadic_thing
第二次递归调用后打印的值会发生变化。 The argument b
is replicated 3 times; 参数
b
被重复3次; its type is also the same (ie Base<Value>
). 其类型也相同(即
Base<Value>
)。 It seems that somehow, after the second call, the arguments no longer refer to some valid memory. 似乎在第二次调用后,这些参数不再引用某些有效内存。
How is this possible? 这怎么可能?
Pass by reference: 通过参考传递:
void do_variadic_thing(const Base<Derived>& b, const Args&... args)
^
here
您正在按值传递第二个/第三个实例-考虑如何构造副本。
The type of the variable b
is Base<Value> const&
, but the object it refers to is of type Value
. 变量
b
的类型为Base<Value> const&
,但它引用的对象的类型为Value
。 When you copy b
to replicate it inside do_thing
, you are slicing it; 当您复制
b
以在do_thing
复制它时,您正在对其进行切片 ; that is, only copying the Base<Value>
part. 也就是说,仅复制
Base<Value>
部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.