I have some questions about the CRTP. Let's say I have the following code
#include <iostream>
// interface
template<class Imp>
class Interface{
public:
inline void print(void){
std::cout<<"value: ";
return asImp().print();
}
private:
typedef Imp Implementation;
inline Implementation& asImp(void){return static_cast<Implementation&>(*this);}
};
// add
class Add:public Interface<Add>{
public:
inline void print(void){std::cout<<value<<std::endl;++value;}
private:
int value;
};
// main
int main(void){
Interface<Add> foo;
foo.print();
foo.print();
}
The output is
value: 0
value: 1
Therefore the variable value
seems to be constructed as 0 by the default constructor. But I don't understand where and when this constructor is called since no object of the derived class is created.
Moreover, let's suppose that I want create value with a different starting value, how can I achieve that using this design pattern?
Obviously I could create an init()
method in the derived class which is called in the constructor of the base class but it wouldn't work for a type which hasn't a default constructor.
Finally, is it possible to forward some arguments pass to the constructor of the base class to the constructor of the derived class?