开发者

boost signal with min_element

开发者 https://www.devze.com 2023-03-16 21:19 出处:网络
I am writing a little example to try to understand multiple return values of boost::signal. However, the result seems weired to me.

I am writing a little example to try to understand multiple return values of boost::signal. However, the result seems weired to me.

#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;
}

The first min_element would output "3" while the second would output "2". Obviously "2" is the smallest number among those three. I don't know what's wrong with the first one. In operator() I also tried to iterate from first to last and I got the sequence "3,4,2" which seems correct. But why would min_element give me "3" instead?

The code was compiled with VS2010 SP1. The version of Boost is 1.46.1 which is the latest one.

Thanks in advance.

开发者_如何学Go

Michael


Weird. Replacing operator():

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

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

    return T();
}

Works, but as soon as you dereference result, first and result both get stuck at 3. This is what std::min_element is doing; I found my implementation's source and stripped it down to what you've seen above.

I have no idea what's going on.

This is Boost 1.38.0 on GCC 4.5.0.

0

精彩评论

暂无评论...
验证码 换一张
取 消