I have a set of functions that work on templated classes, but don't rely on the templated parts of the class.
Templating the function and allowing it to deduce the types would work, but would then compile to multiple functions.
#include <iostream>
template<typename T>
struct MyStruct {
int a;
T b;
};
bool isLess(MyStruct& lhs, MyStruct& rhs) {
return lhs.a < rhs.a;
}
int main(int argc, char const *argv[])
{
MyStruct<int> x {123, 456};
MyStruct<int> y {789, 123};
std::cout << isLess(x, y) << std::endl;
return 0;
}
Is there a way to achieve this?
There are ways to restrict the types you can use inside a template you write by using specific typedefs inside your template. This will ensure that the compilation of the template specialisation for a type that does not include that particular typedef will fail, so you can selectively support/not support certain types.
The entities of variable, function, struct, and class can have templates, which involve declaration and definition. Creating a template also involves specialization, which is when a generic type takes an actual type. The declaration and the definition of a template must both be in one translation unit.
Function templates are special functions that can operate with generic types. This allows us to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type. In C++ this can be achieved using template parameters.
main cannot be a function template; it must be a function.
Refactor the fields that do not depend on T
in another class. Make MyStruct<T>
inherit from it:
struct MyStructBase
{
int a;
};
template<typename T>
struct MyStruct : MyStructBase
{
T b;
};
bool isLess(MyStructBase& lhs, MyStructBase& rhs) {
return lhs.a < rhs.a;
}
int main(int argc, char const *argv[])
{
MyStruct<int> x {123, 456};
MyStruct<int> y {789, 123};
std::cout << isLess(x, y) << std::endl;
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With