Matt Matt - 21 days ago 5
C++ Question

C++ Function for struct regardless of template types

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?

Answer

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;
}