如何为两个已经存在的类型创建重载? 我现在试图模拟C++中的管道,其中通过管道将某个参数作为lambda函数的参数。
但是当我试图在向量和函数指针之间的操作符上创建全局重载时,我无法重新定义操作符,因为(我假设)不能重载两个基本类型 以下是我一直在尝试的:如何为两个已经存在的类型创建重载? 我现在试图模拟C++中的管道,其中通过管道将某个参数作为lambda函数的参数。,c++,operator-overloading,C++,Operator Overloading,但是当我试图在向量和函数指针之间的操作符上创建全局重载时,我无法重新定义操作符,因为(我假设)不能重载两个基本类型 以下是我一直在尝试的: #include <iostream> using namespace std; void operator |( int *vet , void(*func)(int)){ for ( int i = 0 ; i < 10 < i++){ func(vet[i]); } int main(int arg
#include <iostream>
using namespace std;
void operator |( int *vet , void(*func)(int)){
for ( int i = 0 ; i < 10 < i++){
func(vet[i]);
}
int main(int argc, char **argv)
{
int tab[10] = { 1, 2, 3, 2, 3, 4, 6, 0, 1, 8 };
tab | []( int x ) { cout << x*x << endl; };
return 0;
}
#包括
使用名称空间std;
void运算符|(int*vet,void(*func)(int)){
对于(int i=0;i<10tab |[](int x){cout标准中已经有一个表示函数对象的好类:。您可以使用它来满足运算符重载()的要求:
但它仍然令人困惑——它不是Bash代码,是吗
最好的、可读性最好的解决方案是使用一些程序员建议的标准函数和习惯用法,甚至是普通的for
循环
#include <algorithm>
std::for_each(std::begin(tab), std::end(tab), []( int x ) { cout << x*x << endl; });
#包括
std::for_each(std::begin(tab),std::end(tab),[](int x){cout提交我的答案后,我获得了让我觉得有点愚蠢的解决方案,它是:
#include <algorithm>
void operator | ( const auto& v, auto map ) {
for_each( begin( v ), end( v ), map );
}
#包括
无效运算符|(常数自动&v,自动映射){
对于每个单元(开始(v)、结束(v)、映射);
}
您的重载毫无意义,因为|
运算符必须返回一个值。您无法真正更改运算符的基本方面。此外,您所需的内容已由函数(或使用)实现.非常感谢,这正是我想要的!至于语法,我同意它看起来很可怕,但这是我的任务,所以我不得不这样做
#include <algorithm>
std::for_each(std::begin(tab), std::end(tab), []( int x ) { cout << x*x << endl; });
#include <algorithm>
void operator | ( const auto& v, auto map ) {
for_each( begin( v ), end( v ), map );
}