简体   繁体   English

const成员函数的std函数包装器

[英]std functional wrapper of const member function

#include <functional>
#include <iostream>

struct Foo {
    Foo(int num) : num_(num) {}
    void print_add(int i) const { std::cout << num_+i << '\n'; }
    int get_num(int i) { return num_;}
    void set_num(int i) { num_ = i;}
    int num_;
};
int main() {
    std::function<int(const Foo *, int)> f_get_num;
    f_get_num = &Foo::get_num;
    return 0;
}

This will generate a error, error: invalid conversion from 'const Foo*' to 'Foo*' [-fpermissive] at line f_get_num = &Foo::get_num . 这将生成错误, error: invalid conversion from 'const Foo*' to 'Foo*' [-fpermissive]在行f_get_num = &Foo::get_numerror: invalid conversion from 'const Foo*' to 'Foo*' [-fpermissive] Foo::get_num type is int (Foo:: *fp)(int) . Foo::get_num类型是int (Foo:: *fp)(int) Can anybody explain it? 任何人都可以解释一下吗? Thanks. 谢谢。

You cannot call non- const functions on const objects. 您不能在const对象上调用非const函数。 You can pass const Foo* to f_get_num , but Foo::get_num takes non-const implicit this . 你可以通过const Foo*f_get_num ,但Foo::get_num采取非const的隐含this

The following two calls are just as illegal: 以下两个电话同样是非法的:

Foo foo;
Foo const* const_ptr = &foo;

const_ptr->get_num(42);
f_get_num(const_ptr, 42); // results in const_ptr->get_num(42)

You can declare your get_num to be const : 您可以将get_num声明为const

int get_num(int i) const { return num_;}

And then your code will work correctly. 然后您的代码将正常工作。

The other way is to make your f_get_num take non- const parameter, but that's not the way to go when your function is a getter and shouldn't modify the object. 另一种方法是让你的f_get_num取非const参数,但当你的函数是一个getter并且不应该修改对象时,这不是你要去的方法。

std::function<int(Foo*, int)> f_get_num;
f_get_num = &Foo::get_num;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM