标准运算符的函数指针
function pointers of standard operators
这是一个后续问题,函数指针使用"<"作为运算符,仍然没有答案。
这与我在这里找到的答案代码非常相似:是否可以获取内置标准运算符的功能指针?
问。在上面的链接中+
被用作std::operator+
那么为什么我不能使用std::operator<
呢?
目的是不要使用参数较少的重载函数,而是用std::library
中的某些内容替换
template <typename T>
bool compare (T a,T b,bool (*compareFunction) (T ,T ))
{
return compareFunction (a,b);
}
template <typename T>
bool compare (T a,T b)
{
return a<b;
}
bool m (int a ,int b)
{
return a<b;
}
int main ()
{
int a=5,b=6;
/*
* This Works
*/
if (compare<int>(a,b,m))
cout<<"Sucess";
else
cout<<"Post this in stack overflow ";
/*
* This also Works
*/
if (compare<int>(a,b))
cout<<"Sucess";
else
cout<<"Post this in stack overflow ";
/*
* Adding this gives compile error.
*/
if (compare<int> (a,b,&std::operator<))
cout<<"sucess";
else
cout<<"Post in Stackoverflow ";
return 0;
}
您必须区分内置运算符和重载运算符。内置运算符是仅具有基本类型(整数、布尔值、浮点数、指针(的操作数的运算符。
例如:
int a = 9, b = 7;
a + b; <-- built-in plus operator
6 + 5; <-- built-in plus operator
C++提供了为用户定义类型(即类(定义运算符的可能性。 std::string
是一个类(由库定义,但这并不重要(。所以如果我们写这个:
std::string a = "asdf", b = "qwert";
a + b; <-- this is not built-in operator.
为了使上述内容进行编译,必须有一个加号运算符的声明和定义,该运算符对字符串类型的两个对象进行操作。碰巧标准库定义了这样的运算符:std::operator+(std::basic_string(。所以这个:
std::string a = "asdf", b = "qwert";
a + b;
其实是这样的:
std::string a = "asdf", b = "qwert";
std::operator+(a, b); <-- call to overloaded operator (see this as a function call)
内置运算符不是函数。重载运算符的行为类似于函数。
内置运算符只有基本类型作为操作数,其功能由标准定义(不能重新定义int + int
的作用(。
重载运算符必须至少有一个用户定义类型的操作数。
让我们来看看一些实际的例子:
template <class T, class Compare>
bool compare (T a, T b, Compare comp) {
return comp(a,b);
}
我已将您的函数指针替换为模板参数。因此,这可以是函数指针、函数引用或函数对象。
你有什么选择来称呼它,T
是int
?好吧,您当然不能让操作员通过comp
.所以你必须有一个函数或一个函数对象(见下面的链接(。
// function
bool intCompareLess(int a, int b) {
return a < b;
}
compare(3, 5, intCompareLess);
// function object
class IntComparatorLess {
public:
// this is a function call operator overload
bool operator()(int a, int b) {
return a < b;
}
};
compare(3, 5, IntComparatorLess());
// or don't reinvent the wheel:
compare(3, 5, std::less<int>()); // std::less is somehow similar with IntComparatorLess
如果将比较与T
称为用户定义类型,该怎么办
class MyClass {
public:
int x, y;
};
现在你有一个额外的选择:定义一个运算符并将其作为参数传递:
bool operator<(MyClass c1, MyClass c2) {
if (c1.x == c2.x)
return c1.y < c2.y;
return c1.x < c1.x
}
MyClass a, b;
compare(a, b, (bool (*)(MyClass, MyClass))operator<);
有用: C++函子 - 及其用途
相关文章:
- 如何正确编写指针函数声明?
- C++常规指针函数或模板
- 如何重新定义 C++ 指针函数?
- C++ 指向其他类函数的指针函数
- 指针到指针函数参数
- 将指向成员的指针函数传递到模板中
- C++ 在 none 常量指针函数中返回一个常量指针
- 如何使用指针函数编写/读取数组
- 是C 中的函数指针函数对象
- 如何从另一个类调用指向成员的指针函数
- 如何声明采用指向成员的指针函数的函数
- 如何构造一个以可变参数指针函数作为成员的类?
- c 通过值或指针函数语法
- 将typedef方法作为指针函数传递
- 从 Main 中的双指针函数打印出指针数组
- strcpy 对指针函数的引用
- 这是否仍然声明一种指针函数的别名?
- 将指向成员的指针函数与 std::shared_ptr 结合使用
- 'Incomplete type' 为标准::函数声明指向成员的指针函数模板参数时出错
- 从注入进程的 DLL 调用函数并更改指针函数的地址