是否可以获取内置标准运算符的函数指针?

πάν*_*ῥεῖ 15 c++ operators

我想引用内置运算符的函数指针,但我不知道如何指定特定的类型重载.

我有以下模板类签名:

template<typename ParamsType, typename FnCompareType>
class MyAction
{
public:
    MyAction(ParamsType& arg0, ParamsType& arg1, FnCompareType& fnCpmpare) 
    : arg0_(arg0), arg1_(arg1), fnCompare_(fnCpmpare) {}

    bool operator()()
    {
        if((*fnCompare_)(arg0_,arg1_)
        {
            // do this
        }
        else
        {
            // do s.th. else
        }
    }

private:
    ParamsType& arg0_;
    ParamsType& arg1_;
    FnCompareType& fnCompare_;
}
Run Code Online (Sandbox Code Playgroud)

并希望使用这样的语法:

void doConditional(int param1, int param2)
{
    MyAction<int,&::operator>=> action(param1,param2);
    if(action())
    {
        // Do this
    }
    else
    {
        // Do that
    }
}
Run Code Online (Sandbox Code Playgroud)

但那不编译:

error: ‘::operator>=’ has not been declared
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能引用这种内在的静态操作?

Pix*_*ist 22

内置运营商

为什么你不能有它们的函数指针:

C++ 11,§13.6/ 1,[over.built]

表示本条款定义的内置运算符的候选运算符函数在本子条款中规定.这些候选函数参与 13.3.1.2中描述的运算符重载解析过程,并且不用于其他目的.

内置运算符(内置类型的运算符)不是真正的运算符函数.所以你不能有指向它们的函数指针.您也无法使用operator<(A,B)语法调用它们.它们只参与重载决策,但编译器会将它们直接转换为适当的asm/machine指令,而不需要任何"函数调用".

解决这个问题的方法:

user1034749已回答了这个问题,但为了完整性:

该标准在§20.8,[function.objects]中定义了许多函数对象,即

  • 算术运算
  • 比较
  • 逻辑运算
  • 按位运算

函数对象是函数对象类型的对象.在人们期望将指向函数的指针传递给算法模板的地方(第25条),接口被指定为接受函数对象.这不仅使算法模板与函数指针一起使用,而且使它们能够使用任意函数对象.

C++ 11,§20.8.5,[比较]

  • 等于
  • 不等于
  • 更大,更少
  • greater_equal
  • less_equal

这些是模板化的函数对象,它们在operator()函数中衰减为类似的运算符.它们可以用作函数指针参数.

user1034749是对的,我想说明:没有其他办法,这些与'原始'函数指针的使用完全等效.参考给出.

标准类类型运算符

您可以使用标准库运算符作为函数指针(它们作为"实际函数"出现).

但是你必须引用模板的相应实例.编译器需要适当的提示来推导出正确的模板.

这适用于MSVC 2012使用operator+std::basic_string

template<class Test>
Test test_function (Test const &a, Test const &b, Test (*FPtr)(Test const &, Test const &))
{
   return FPtr(a, b);
}

int main(int argc, char* argv[])
{
   typedef std::char_traits<char> traits_t;
   typedef std::allocator<char> alloc_t;
   std::basic_string<char, traits_t, alloc_t> a("test"), b("test2");
   std::cout << test_function<std::basic_string<char, traits_t, alloc_t>>(a, b, &std::operator+) << std::endl;
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果test_function遗漏了模板参数,那么这将失败(至少对于MSVC 2012).


fgh*_*ghj 9

您可以使用与C++标准库中使用的解决方案相同的解决方案:

std::sort (numbers, numbers+5, std::greater<int>());
Run Code Online (Sandbox Code Playgroud)

哪里更大

template <class T> struct greater : binary_function <T,T,bool> {
    bool operator() (const T& x, const T& y) const {return x>y;}
};
Run Code Online (Sandbox Code Playgroud)

在您的案例中http://www.cplusplus.com/reference/functional/greater_equal/

关于建成运营商的参考.

您可以为任何类引用现有的operator <(当然,如果它们不是私有的,受保护的,或者您的类/函数不是朋友).但是opeator <for builtin types(bool,short,int,double)是不可能引用的.事件,如果没有看C++标准,你可以从我上面的文字中看到.