c++ - 用 min_element boost 信号

标签 c++ boost

我正在写一个小例子来尝试理解 boost::signal 的多个返回值。然而,结果对我来说似乎很奇怪。

#include <boost/signal.hpp> 
#include <iostream> 
#include <algorithm> 

int func1() 
{ 
    return 3; 
} 

int func2() 
{ 
    return 4; 
} 

int func3()
{
    return 2;
}

template <typename T> 
struct min_element 
{ 
    typedef T result_type;  //result_type is required by boost::signal

    template <typename InputIterator> 
    T operator()(InputIterator first, InputIterator last) const 
    {
        std::cout<<*std::min_element(first, last)<<std::endl;  //I got 3 here
        return T(first, last); 
    } 
}; 

int _tmain(int argc, _TCHAR* argv[])
{
    boost::signal<int (), min_element<std::vector<int> > > s; 
    s.connect(func1); 
    s.connect(func2); 
    s.connect(func3);
    std::vector<int> v = s();
    std::cout<<*std::min_element(v.begin(),v.end())<<std::endl; //I got 2 here
    return 0;
}

第一个 min_element 将输出“3”,而第二个将输出“2”。显然“2”是这三个中最小的数字。我不知道第一个有什么问题。在 operator() 中,我也尝试从头到尾迭代,我得到了看起来正确的序列“3,4,2”。但为什么 min_element 会给我“3”呢?

代码是用VS2010 SP1编译的。 Boost 的版本是 1.46.1,这是最新的。

提前致谢。

迈克尔

最佳答案

奇怪。替换 operator():

T operator()(InputIterator first, InputIterator last) const 
{
    InputIterator result = first;

    while (++first != last) {
//      *result;
        std::cout<<*first<<std::endl;
    }

    return T();
}

有效,但是一旦您取消引用 resultfirstresult 都会卡在 3。这就是 std::min_element 正在做;我找到了我的实现源并将其简化为您在上面看到的内容。

我不知道发生了什么。

这是 GCC 4.5.0 上的 Boost 1.38.0。

关于c++ - 用 min_element boost 信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6566426/

相关文章:

c++ - C2400 内联汇编语法错误,对比 2015

c++ - 允许模板中不完整类型的技巧?

c++ - sqlite CREATE INDEX exec 返回错误

c++ - 类构造函数上 boost::shared_ptr 的默认值

c++ - 套接字关闭但 session 引用未被正确销毁

c++ - 如何压缩(组合迭代器)不处理 boost::prior

c++ - 在没有互斥锁的情况下并发追加到列表尾部

c++ - 如何在无捕获的 lambda 中初始化一个范围内的项目,C++

c++ - 我如何 grok boost spirit 编译器错误

c++ - 如何使用 boost.process 重定向标准输入和标准输出