Template constructor in a non-template class
Sometimes it is required to derive a new class from a base class with constructors that can take many types and perform internal conversion. An easy way to avoid errors due to by-hand writing forwarding constructors for each of the types is to use a constructor in the derived class with a template parameter. This works fine even in a non-template class, i.e., non of the data members of the class are dependent on template parameters. This is an example:
// Bojan Nikolic <bojan@bnikolic.co.uk>
#include <vector>
#include <iostream>
struct B {
size_t i;
B (size_t i):
i(i)
{}
B (const std::vector<double> &c):
i(c[0])
{};
};
struct D : public B {
template<class T> D(T c):
B(c)
{
}
};
int main(void)
{
std::vector<double> x(3,3);
D d(5);
std::cout<<d.i<<std::endl;
D d2(x);
std::cout<<d2.i<<std::endl;;
}