I have a small C++ class which wraps type information for some basic types; a simplified version looks like this:
struct TypeInfo {
TypeInfo(std::size_t elm_size, const std::string& type_name) :
elm_size(elm_size),
type_name(type_name)
{}
std::size_t elm_size;
std::string type_name;
}
TypeInfo double_info(sizeof double, "double");
TypeInfo int_info(sizeof int, "int");
This works - but I would love to be able to instantiate the TypeInfo
object based on normal C++ templating; i.e. something like this:
TypeInfo<double> double_info; // <- This does not work
Since the class as such does not contain any T
- it is not really a templated class - but rather a convenient instantiation method. When this is contained in a function which is truly templated:
void vector_operation(const std::vector<T>& data) {
TypeInfo<T> type_info; // <- This does not work!
}
it would be really helpful if I could instantiate TypeInfo
instance based on a template parameter. Since I only need to cover a handful of fundamental types - float, double, int
and char
I would be more than happy to specialize the handful of types explicitly.
Update: @nathan_oliver suggested to make the class as a whole a template, and then use sizeof(T)
to determine the element size. The problem with that solution (as I see it) - is that the user still needs to supply the type_name
string (and some more type specific information) - I would like specialize the few types I need - and then fully specify:
template <typename T>
struct TypeInfo {
TypeInfo();
std::size_t elm_size;
std::string type_name;
}
And then in the .cpp file:
template<>
TypeInfo::TypeInfo<double>() {
this->elm_size = sizeof(double);
this->type_name = "double";
}
template<>
TypeInfo::TypeInfo<int>() {
this->elm_size = sizeof(int);
this->type_name = "int";
}
but this does not even compile:
type_info.cpp:46:5: error:
invalid use of template-name ‘TypeInfo’ without an argument list
TypeInfo::TypeInfo()