1

我可以std::bind使用实例正常工作,但无法使用对接口的引用(纯虚拟类)。

我需要这个功能来对接口进行惰性评估(它将在运行时引用具体实例)。

编译错误

In file included from /usr/include/c++/4.7/functional:56:0,
                 from junk.cpp:1:
/usr/include/c++/4.7/tuple: In instantiation of ‘struct std::_Head_base<0ul, Integer, false>’:
/usr/include/c++/4.7/tuple:215:12:   required from ‘struct std::_Tuple_impl<0ul, Integer>’
/usr/include/c++/4.7/tuple:374:11:   required from ‘class std::tuple<Integer>’
/usr/include/c++/4.7/functional:1148:29:   required from ‘struct std::_Bind<std::_Mem_fn<int (Integer::*)()const>(Integer)>’
junk.cpp:24:42:   required from here
/usr/include/c++/4.7/tuple:166:13: error: cannot declare field ‘std::_Head_base<0ul, Integer, false>::_M_head_impl’ to be of abstract type ‘Integer’
junk.cpp:4:8: note:   because the following virtual functions are pure within ‘Integer’:
junk.cpp:6:14: note:    virtual int Integer::getInt() const
make: *** [junk] Error 1

有没有办法让它工作std::bind?如果没有,有什么东西在提升吗?

代码

#include <functional>
#include <iostream>

struct Integer
{
    virtual int getInt() const = 0;
};

struct IntImpl : public Integer
{
    virtual int getInt() const { return 42; }
};

int
main( int argv, char* argc[] )
{
    // works fine
    IntImpl  x;
    auto f = std::bind( &Integer::getInt, x );
    std::cerr << f() << std::endl;

    // need an interface because I won't know if concrete class will be x
    // or something else until run-time, but y will refer to that instance
    Integer& y = x; 
    // next line won't compile
    auto g = std::bind( &Integer::getInt, y );
    std::cerr << g() << std::endl;
}
4

1 回答 1

1

只需使用:

auto g = std::bind( &Integer::getInt, &y );

(在之前添加地址运算符y

于 2013-01-06T20:37:13.267 回答