我想引用内置运算符的函数指针,但我不知道如何指定具体的类型重载。
我有以下模板类签名:
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_;
}
并且想使用这样的语法:
void doConditional(int param1, int param2)
{
MyAction<int,&::operator>=> action(param1,param2);
if(action())
{
// Do this
}
else
{
// Do that
}
}
但这并不能编译:
error: ‘::operator>=’ has not been declared
我能做些什么来引用这种固有的静态操作?
最佳答案
内置运算符
为什么你不能拥有它们的函数指针:
C++11,§13.6/1,[over.built]
The candidate operator functions that represent the built-in operators defined in Clause 5 are specified in this subclause. These candidate functions participate in the operator overload resolution process as described in 13.3.1.2 and are used for no other purpose.
内置运算符(用于内置类型的运算符)不是真正的运算符函数。所以你不能让函数指针指向它们。您也不能使用 operator<(A,B)
调用它们句法。
它们只参与重载决策,但编译器会将它们直接翻译成适当的 asm/机器指令,而无需任何类型的“函数调用”。
解决这个问题的方法:
user1034749 has already answered这个问题,但为了完整性:
该标准在§20.8 [function.objects] 中定义了很多函数对象,即
- 算术运算
- 比较
- 逻辑运算
- 位运算
A function object is an object of a function object type. In the places where one would expect to pass a pointer to a function to an algorithmic template (Clause 25), the interface is specified to accept a function object. This not only makes algorithmic templates work with pointers to functions, but also enables them to work with arbitrary function objects.
C++11,§20.8.5,[比较]
- equal_to
- not_equal_to
- greater, less
- 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;
}
如果 test_function
的模板参数被遗漏以推断这将失败(至少对于 MSVC 2012)。
关于c++ - 是否可以获取内置标准运算符的函数指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27606889/