gpt4 book ai didi

c++ - 广义排序函数和使用 binary_function

转载 作者:行者123 更新时间:2023-11-28 07:23:26 30 4
gpt4 key购买 nike

template<class T>
struct gSorting : public std::binary_function<T, T,bool> {
bool operator() (int number, int n2)
{
cout << "int" << endl;
return (number<n2);
}
bool operator() (double number, double n2)
{
cout << "double" << endl;
return (number<n2);
}
bool operator() (const MYClass& obj1, const MYClass& obj2)
{
return (obj1.element<obj2.element);
}
};

int main () {
gSorting<int> sorting_object;

std::cout << std::boolalpha << sorting_object (2.0f, 4.3f) << ".\n";
std::getchar();
return 0;
}

这段代码有什么问题吗?它是通用的吗?或者是否有更好的方法来执行通用排序算法以包括我使用的所有类

它编译,输出指向 double 这很好,但是我怎样才能使它成为一个模板,而不必在声明中指定输入类型?

gSorting sorting_object;

------------^^^^ 我们不需要任何特定类型?我说得对吗

输出:

enter image description here

最佳答案

我会亲自为二元谓词定义一个类模板,并根据需要对其进行专门化,例如:

template <typename T>
struct gSorting
: std::binary_function<T const&, T const&, bool> // not really needed
{
bool operator()(T const& t0, T const& t1) const {
return t0 < t1;
}
};
template <>
struct gSorting<MyClass>
: std::binary_function<MyClass const&, MyClass const&, bool>
{
bool operator()(MyClass const& c0, MyClass const& c1) const {
return c0.element < c1.element;
}
};

在实际实现中,泛型版本的参数类型可能应该根据类型的种类和/或基于特征的特征来决定参数是按值还是按 const& 传递然后根据需要专门化。例如:

template <typename T>
struct argument_type
{
typedef typename std::conditional<
std::is_fundamental<T>::value, T, T const&>::type type;
};

template <typename T>
struct gSorting
: std::binary_function<typename argument_type<T>::type,
typename argument_type<T>::type, bool>
{
typedef typename argument_type<T>::type arg_type;
bool operator()(arg_type t0, arg_type t1) const {
return t0 < t1;
}
};

关于c++ - 广义排序函数和使用 binary_function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19083745/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com