Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;_C++ - Fatal编程技术网

C++ C++;

C++ C++;,c++,C++,基本上我想创建一组函数对象。 在python中,如果我们这样做: def func(): print "a" a = func b = func fset = set() fset.insert(a) fset.insert(b) 在这种情况下,fset将只有一个函数,因为a和b在python中是相同的。 但是在C++中,如果我为相同的函数创建函数对象,A和B都是集合的两个不同对象。两个具有相同功能的对象是否有相同的方式 在C++中: void func(){ cout &l

基本上我想创建一组函数对象。 在python中,如果我们这样做:

def func():
    print "a"

a = func
b = func
fset = set()
fset.insert(a)
fset.insert(b)
在这种情况下,fset将只有一个函数,因为a和b在python中是相同的。 但是在C++中,如果我为相同的函数创建函数对象,A和B都是集合的两个不同对象。两个具有相同功能的对象是否有相同的方式

在C++中:

void func(){
    cout << "a";
}

function<void()> a = bind(func);
function<void()> b = bind(func);
void func(){

cout如果只有void函数(或者所有函数都有相同的签名),只需使用C类型函数指针作为
std::set
的模板类型

这将起作用,并且作为一个额外的无类型擦除开销
std::function

void func() {}
void func2() {}

using fPtrType = void(*)(); // convenience type  

int main()
{
    std::set<fPtrType> fset;
    fPtrType a = func;
    fPtrType b = func;
    fset.emplace(a);
    fset.emplace(b);
    fset.emplace(func2);

    std::cout << fset.size();  // prints 2
    return 0;
}
void func(){}
void func2(){}
使用fPtrType=void(*)(;//方便类型
int main()
{
std::set-fset;
fPtrType a=func;
fPtrType b=func;
fset.emplace(a);
fset.emplace(b);
fset.侵位(功能2);

std::cout
a
b
本质上是指向同一对象的两个指针,而不是同一类的两个实例。您可以使用
std::set
,也可以使用智能指针-它的行为方式类似。但在这种情况下,每次创建函数a=function();函数b=function()的指针时也是如此;a和b仍然有不同的指针,对吗?根据定义,一个集合包含彼此不同的值。当你建议使用“相同的函数”时,不清楚你在这里说的是什么也许你应该用一些C++代码来备份你的问题来说明你的问题。你说“创建一个指针”,但是你的代码实际上并没有创建任何指针。
-这在语法上似乎无效,可能无法编译。@IgorTandetnik他们正在谈论你的注释,其中存储了
std::function*
,如果a和b的作用域不同,这也可以吗?@250你的意思是什么。