当前位置: 动力学知识库 > 问答 > 编程问答 >

C++ how to overload operators for member variables

问题描述:

If I have a struct:

typedef struct Foo

{

std::function<bool()> func;

}Foo;

and I have a void function

void bar(){std::cout << "hey";}

and I want to be able to do this:

Foo f;

f.func = bar // f.func == func(){std::cout << "hey"; return true;}

网友答案:

The first thing is that the function type for void bar() {} is void() and not bool(), so func should be:

std::function<void()> func;

Second thing: it is unclear what "C++ how to overload operators for member variables" means. If you want to make your code compile then the above change is sufficient. The operator you can overload is void operator()() { func(); } if you want to call f();.

If you want to keep bool() function type and still be able to call void() function then you could use a lambda, which would call bar and return true:

f.func = [](){ bar(); return true;};
分享给朋友:
您可能感兴趣的文章:
随机阅读: