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

这段代码有问题吗?有那么通用吗?或者有没有更好的方法来做一个通用的排序算法来包括我使用的所有类

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

gSorting< int > 排序对象;

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

输出:

在此处输入图像描述

4

1 回答 1

1

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

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;
    }
};
于 2013-09-29T22:14:28.567 回答