简体   繁体   中英

Template function to return template type

I have the following function but my compiler (VS2003) says that the assignement T = .... is illegal. Can someone clarify what I've done wrong? The type of value is a boost::variant. node is a struct.

 template <typename T>
    T find_attribute(const std::string& attribute)
    {

        std::vector<boost::shared_ptr<node> >::iterator nodes_iter = _request->begin();

        for (; nodes_iter != _request->end(); nodes_iter++)
        {
            std::vector<node::attrib>::iterator att_iter = (*nodes_iter)->attributes.begin();
            for (; att_iter != att_iter; (*nodes_iter)->attributes.end())
            {
                if ((*att_iter).key.compare(attribute) == 0) {
                    T = (*att_iter).value;  //T : Illegal use of this type as an expression.
                                    return T; 
                            }

            }

        }
    }

You should declare a variable:

if ((*att_iter).key.compare(attribute) == 0) {
    T temp = (*att_iter).value;  //T : Illegal use of this type as an expression.
    return temp; 
}

T is a type , not a variable name. In the general case, you should declare a variable as mentioned by @sharptooth (this is the usual workflow for any function!).

In your particular case, it's better just to return the value – no additional variable is needed:

return (*att_iter).value;

or, better yet:

return att_iter->value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM