开发者

loop on a map same way as array

开发者 https://www.devze.com 2023-03-14 19:27 出处:网络
I\'m trying to loop on containers(map, set,vector,list) 开发者_开发技巧and array the same way.

I'm trying to loop on containers(map, set,vector,list) 开发者_开发技巧and array the same way. Here is the code:

template<typename TYPE>
void AddXmlOfContAttribute(TYPE *it)
{
    m_ss<<"<SingleNode ";
    AddXmlAttribute("Value" , *it);
    m_ss<<"/>\n";
}



template<typename TYPE1,typename TYPE2>
void AddXmlOfContAttribute(std::pair<TYPE1,TYPE2> tpair)
{
    m_ss<<"<MapNode ";
    AddXmlAttribute("key"   , tpair->first);
    AddXmlAttribute("Value" , tpair->second);
    m_ss<<"/>\n";
}




template<typename TYPE>
    void AddContainerToXml(std::string str, TYPE it_begin ,  TYPE it_end)
    {
        if(it_begin != it_end)
        {
            m_ss<<"<"<<str<<">\n";

            //std::for_each(it_begin , it_end, AddXmlOfContAttribute);

            for( ; it_begin != it_end ; it_begin++)
                AddXmlOfContAttribute(it_begin);

            m_ss<<"</"<<str<<">\n";
        }
    }

I get the following error:

In member function ‘void AddElementToBackupFileFunctor::AddContainerToXml(CrString, TYPE, TYPE) [with TYPE = std::_Rb_tree_const_iterator >]’ instantiated from here error: no matching function for call to

AddElementToBackupFileFunctor::AddXmlOfContAttribute(std::_Rb_tree_const_iterator >&)’

How do i do it in normal loop? Bonus question :How do i do it in for_each loop?


So, in short, I have constructed an example that should explain all you need here.

In order to do what you want, you have to first change your handlers to structs with static methods (this is required because you cannot partially specialize function templates, see here):

template<typename TYPE>
struct value_handler {
    static void AddXmlOfContAttribute(AddElementToBackupFileFunctor& context, 
                                      TYPE value) {
        // handle normal values here
        // context replaces this-pointer
    }
};

// partial specialization for pairs
template<typename TYPE1, typename TYPE2>
struct value_handler<std::pair<TYPE1, TYPE2> > {
    static void AddXmlOfContAttribute(AddElementToBackupFileFunctor& context, 
                                      std::pair<TYPE1, TYPE2> value) {
        // handle values that are pairs here
        // context replaces this-pointer
    }
};

The value-parameters cannot be references, because that would screw up std::bind1st (a workaround using Boost is described here). To use this with std::for_each, do the following:

std::for_each(begin, end, std::bind1st(
    std::ptr_fun(&AddElementToBackupFileFunctor::value_handler<typename TYPE::value_type>::AddXmlOfContAttribute), 
    *this));


The compilation error comes from this line:

AddXmlOfContAttribute(it_begin);

This should be:

AddXmlOfContAttribute(*it_begin);

I am a moron I didn't realize the first overload... that should be the reference as sc said.

0

精彩评论

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