C ++ function for structure regardless of template types

I have a set of functions that work on template classes, but do not rely on the template parts of the class.

Function templates and allowing it to infer types will work, but will then be compiled for 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 any way to achieve this?

+8
c ++ templates
source share
3 answers

Refactoring fields that are independent of 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; } 
+12
source share

You can use inheritance:

 struct MyStructBase { int a; }; template<typename T> struct MyStruct : public MyStructBase { T b; }; bool isLess(MyStructBase& lhs, MyStructBase& rhs) { return lhs.a < rhs.a; } 
+9
source share

I would do this:

 template<typename L, typename R> auto isLess(L&& lhs, R&& rhs) -> decltype(std::declval<L>().a < std::declval<R>().a) { return std::forward<L>(lhs).a < std::forward<R>(rhs).a; } 

This will work regardless of the relationship between your types and will not compile into multiple functions (see the last paragraph). This will allow you to use any types that have a member a that is less than comparable.

Function templates and allowing it to infer types will work, but will then be compiled for multiple functions.

Not bad. It is even better than this, it will compile without any function, since any sane compiler (even msvc) will fully integrate this function.

+1
source share

All Articles