Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/153.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++ 使boost::function引用我的函数对象_C++_Boost_Struct_Boost Function - Fatal编程技术网

C++ 使boost::function引用我的函数对象

C++ 使boost::function引用我的函数对象,c++,boost,struct,boost-function,C++,Boost,Struct,Boost Function,我想将实现operator()的结构传递给接受boost::function的函数。此结构跟踪调用它的次数 struct CallCounter { CallCounter() : count( 0 ) {} void operator()() { // do stuff cout << "count is at " << count << endl; ++count; }

我想将实现
operator()
的结构传递给接受
boost::function
的函数。此结构跟踪调用它的次数

struct CallCounter
{
    CallCounter() : count( 0 ) {}
    void operator()()
    {
        // do stuff
        cout << "count is at " << count << endl;
        ++count;
    }

    int count;
};

即使调用
计数器
,它也会打印出正确的
计数
。我知道
boost::function
正在复制我的
struct计数器
。有没有办法通过引用传递它,这样之后,
count
就是正确的数字?

我看到您使用的是
boost::function
。这里实际上没有必要,您可以使用模板并通过引用传递函子:

template<typename Functor>
void callNTimes( int n, Functor& func )
{
    for ( int i = 0; i < n; ++i )
        func();
}
模板
void callNTimes(int n,Functor&func)
{
对于(int i=0;i

我看到您正在使用
boost::function
。这里实际上没有必要,您可以使用模板并通过引用传递函子:

template<typename Functor>
void callNTimes( int n, Functor& func )
{
    for ( int i = 0; i < n; ++i )
        func();
}
模板
void callNTimes(int n,Functor&func)
{
对于(int i=0;i

boost
函数
stuff默认采用变量值,与普通函数非常相似。如果希望函数使用对
调用计数器的引用,则必须明确告诉它:

callNTimes( 20, boost::ref(counter) );
请看这里:

如果您想要一个常量引用,但是没有
boost::rref
(这几乎与一个值相同,但是一次性使用。
函数
是多用途的,因此没有移动)。此外,从C++11开始,所有这些都在
std
名称空间中


此外,如果可能的话,Jefffrey的建议通常被认为是编写此类代码的更好方法。不过,它可能会对编译时间产生负面影响。

boost
函数
默认情况下采用变量值,与普通函数非常相似。如果希望函数使用对
调用计数器的引用,则必须明确告诉它:

callNTimes( 20, boost::ref(counter) );
请看这里:

如果您想要一个常量引用,但是没有
boost::rref
(这几乎与一个值相同,但是一次性使用。
函数
是多用途的,因此没有移动)。此外,从C++11开始,所有这些都在
std
名称空间中


此外,如果可能的话,Jefffrey的建议通常被认为是编写此类代码的更好方法。不过,这可能会对编译时间产生负面影响。

我没有充分阅读该问题:(@MooingDuck,你应该将其作为答案发布。我更喜欢模板。;)我没有充分阅读该问题:(@MooingDuck,你应该将其作为答案发布。我更喜欢模板。)我想我推荐C++11中的
函子&
,或者C++03中的
常量函子&
/
函子&
对;但是作为一个总体想法,我绝对支持这个建议。我想我会推荐C++11中的
函子&
,或者C++03中的
常量函子&
/
函子&
对。在这种特殊情况下,在
常量函子&
函子&
之间,只有后者会起作用,而
函子&
实际上变化不大;但总的来说,我绝对赞同这个建议。