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.
What I want to do is to run the print method from a function with a variable number of arguments (do_variadic_thing). 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. The argument b is replicated 3 times; its type is also the same (i.e Base<Value>). It seems that somehow, after the second call, the arguments no longer refer to some valid memory.
How is this possible?