C++函数结构,无论模板类型如何

Mat*_*att 8 c++ templates

我有一组函数可以处理模板化的类,但不依赖于类的模板化部分.

模板化函数并允许它推导出类型会起作用,但会编译成多个函数.

#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;
}
Run Code Online (Sandbox Code Playgroud)

有没有办法实现这个目标?

Vit*_*meo 12

重构不依赖T于另一个类的字段.使MyStruct<T>从它继承:

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;
}
Run Code Online (Sandbox Code Playgroud)


πάν*_*ῥεῖ 9

您可以使用继承:

struct MyStructBase {
    int a;
};

template<typename T>
struct MyStruct : public MyStructBase {
    T b;
};


bool isLess(MyStructBase& lhs, MyStructBase& rhs) {
    return lhs.a < rhs.a;
}
Run Code Online (Sandbox Code Playgroud)