Reputation: 2830
So I have a wrapper for the default C++ vector
. My class is a template class like vector so it basically works with all types I want to support. Now I have one issue. I would like to add a function to my wrapper that let's me save my internally stored vector
to file. However, the library that I am using to do this has a poor C++ interface to C functions and requires me to pass over a void*
and an entry of a predefined list of types.
Let's say I have the class:
template<class T>
class MyClass
{
dataType type;
std::vector<T> data;
MyClass()
{
//
}
};
And I have three types I want to support (e.g.):
float: floatType
int: intType
char: charType
Questions:
Upvotes: 0
Views: 68
Reputation: 1189
If you only need support these three types, you can use a template function with specialized implementations exactly for them:
template<class T> class MyClass {
...
f();
};
template<> MyClass<float>::f();
template<> MyClass<int>::f();
template<> MyClass<char>::f();
And provide the implementations exactly for these parameters in an associated C++ file. When calling f()
on an instance with another template parameter, the linker will complain about a missing symbol because there is no specialized implementation available.
Upvotes: 2
Reputation: 146
If you only want to support some kinds of types T you could hide the template and provide the types you want:
typedef MyClass<int> MyClass_32s;
typedef MyClass<float> MyClass_32f;
...
After that you could write a wrapper for your c Interface:
void passToCInterface(MyClass_32s& dat)
{
callCInterfaceFunction(static_cast<void*>(&(dat.data)), INT_FLAG);
}
void passToCInterface(MyClass_32f& dat)
{
callCInterfaceFunction(static_cast<void*>(&(dat.data)), FLOAT_FLAG);
}
...
Upvotes: 0