Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Function for struct regardless of template types

Tags:

c++

templates

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?

like image 677
Matt Avatar asked Nov 15 '16 16:11

Matt


People also ask

How will you restrict the template for a specific datatype?

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.

Can struct have template?

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.

What is a templated function C++?

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.

Can we use template in main function?

main cannot be a function template; it must be a function.


1 Answers

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;
}
like image 138
Vittorio Romeo Avatar answered Nov 03 '22 00:11

Vittorio Romeo