C ++ Builder Clang std :: less无法找到重载的运算符<

时间:2018-03-31 22:29:08

标签: c++ std c++builder

以下程序使用经典的C ++ Builder编译器进行编译,但未能使用Clang编译器:

#pragma hdrstop
#pragma argsused

#ifdef _WIN32
#include <tchar.h>
#else
  typedef char _TCHAR;
  #define _tmain main
#endif

#include <stdio.h>
#include <complex>
#include <vector>
#include <algorithm>

typedef std::complex<double> Complex;

bool operator<(const Complex & lhs, const Complex & rhs)
{
    return lhs.real() < rhs.real();
}

void doSort()
{
    std::vector<Complex> vc;
    std::sort(vc.begin(), vc.end());
}


int _tmain(int argc, _TCHAR* argv[])
{
    doSort();
    return 0;
}

它还编译并链接到经典编译器,但是对于Clang编译器失败,如果我添加显式更少的实例:

std::sort(vc.begin(), vc.end(), std::less<Complex>());

到目前为止,如果我编写一个函数对象,我只能编译Clang编译器:

template <typename T>
struct compLess
{
    bool operator()(const T & lhs, const T & rhs) const
    {
        return lhs < rhs;
    }
};

void doSort()
{
    std::vector<Complex> vc;
    std::sort(vc.begin(), vc.end(), compLess<Complex>());
}

这是否符合新的C ++标准?还有什么我需要做的是让std :: less来识别运算符&lt;复杂?

感谢。

1 个答案:

答案 0 :(得分:1)

所涉及的所有类型和模板 - std::vectorstd::complexstd::sortstd::less - 都是namespace std的成员。 the ADL rules中没有任何内容会导致在全局命名空间中进行查找,因为不涉及该命名空间。特别是因为命名空间std包含operator< lot (只是不需要这里的那个)。

另一方面,对于没有固有顺序的类型(如复数)重载比较并不是一个非常好的主意。它们是二维的,通常不适合线性排序。

使用显式仿函数进行排序顺序的“技巧”(并非真正的技巧)是处理此问题的正确方法。所以就这样做。

相关问题