我一直在听C++中的仿函数.有人可以给我一个关于它们是什么的概述以及在什么情况下它们会有用吗?
在Boost Signals库中,它们重载了()运算符.
这是C++中的约定吗?对于回调等?
我在同事的代码中看到了这一点(恰好是Boost的忠实粉丝).在那里的所有Boost善良中,这只会让我感到困惑.
有关这种超载原因的任何见解?
c++ boost operator-overloading functor function-call-operator
我在下面的函数中有一个小的"lambda表达式":
int main()
{
int x = 10;
auto lambda = [=] () { return x + 3; };
}
Run Code Online (Sandbox Code Playgroud)
下面是为上面的lambda表达式生成的"匿名闭包类".
int main()
{
int x = 10;
class __lambda_3_19
{
public: inline /*constexpr */ int operator()() const
{
return x + 3;
}
private:
int x;
public: __lambda_3_19(int _x) : x{_x}
{}
};
__lambda_3_19 lambda = __lambda_3_19{x};
}
Run Code Online (Sandbox Code Playgroud)
由编译器生成的闭包"operator()"是隐式const.为什么标准委员会const默认做到这一点?
我试图理解C语言的一些基础知识.CRC编程语言说
函数调用是一个后缀表达式,称为函数指示符,后跟括号,其中包含可能为空的逗号分隔的赋值表达式列表(Par.A7.17),它们构成函数的参数.
在函数调用中,运算符是什么,操作数是什么?
是()运营商吗?
函数名是操作数吗?
()操作数内的参数是什么?
谢谢.
c kernighan-and-ritchie language-lawyer function-call-operator
我已经看到了operator()STL容器的使用,但它是什么,你什么时候使用它?
例如,我有一个简单的分类器
struct Clf {
x: f64,
}
Run Code Online (Sandbox Code Playgroud)
如果观察值小于x则分类器返回0,如果大于x则分类器返回1.
我现在想要为这个分类器实现call运算符.但是,该函数应该能够将float或vector作为参数.在向量的情况下,输出是0或1的向量,其具有与输入向量相同的大小.它应该像这样工作
let c = Clf { x: 0 };
let v = vec![-1, 0.5, 1];
println!("{}", c(0.5)); // prints 1
println!("{}", c(v)); // prints [0, 1, 1]
Run Code Online (Sandbox Code Playgroud)
我该怎么写呢
impl Fn for Clf {
extern "rust-call" fn call(/*...*/) {
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下?
以下代码片段在 C++23 中合法吗?
#include <memory>
#include <cstdio>
int main()
{
struct custom_deleter
{
static void operator()(int* const ptr)
{
delete ptr;
std::fputs( "Deleted\n", stdout );
}
};
auto ptr { std::unique_ptr<int, decltype(&custom_deleter::operator())> {new int {5},
custom_deleter::operator()} };
}
Run Code Online (Sandbox Code Playgroud)
GCC 似乎对此很满意。不过我想知道它是否符合标准。
另外,为什么删除&from会decltype(&custom_deleter::operator())导致编译错误?这是否意味着Deleter类型模板参数必须是函数指针类型(在本例中void(*)(int*))?
我试图在c ++中重载函数调用操作符,我得到了这个无法解决的编译错误(Visual Studio 2010).
错误符合要求 act(4);
#include <stdio.h>
#include <iostream>
void Test(int i);
template <class T> class Action
{
private:
void (*action)(T);
public:
Action(void (*action)(T))
{
this->action = action;
}
void Invoke(T arg)
{
this->action(arg);
}
void operator()(T arg)
{
this->action(arg);
}
};
int main()
{
Action<int> *act = new Action<int>(Test);
act->Invoke(5);
act(4); //error C2064: term does not evaluate to a function taking 1 arguments overload
char c;
std::cin >> c;
return 0;
}
void Test(int i)
{
std::cout << …Run Code Online (Sandbox Code Playgroud)