Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Clean Up Function Syntax Mess with decltype-2 : Page 2

The funky syntax of a function's return type isn't just unreadable in many cases—it's also a common source of maintenance problems. However, with the new decltype operator your functions will look much cleaner and easier to maintain.


advertisement

The Point of No return
Suppose you have a function template that returns an iterator designating the end of a vector. The body of such a function is trivial:


return myvector.end();

Similarly, the parameter list of the said function is intuitive:




template <class T> /*return type omitted*/ 
 vector_end( vector<T>& myvector);

Here's the snag: In C++98 you must specify the return type in every function declaration. To do that, you must check what the type of the expression myvector.end() is, and copy that type to the function's declaration. After digging into the declarations of all vector::end()overloads, you decide to use the following return type:


template <class T> typename vector<T>::iterator 
vector_end(vector<T>& myvector)
{
 return myvector.end();
}

//usage 
vector<int> vi(5);
vector<int>::iterator itr=vector_end(vi);

This code works fine, but it's not ideal. If the implementer of vector_end() decides to change its parameter to const vector<T>&, the code will break:


template <class T> 
typename vector<T>::iterator //wrong 
vector_end(const vector<T>& myvector)
{
 return myvector.end();
}
vector<int> vi(5);
vector<int>::const_iterator itr=vector_end(vi);//error 

The return type of vector_end() is the problem. Since the parameter is const vector<T>&, you must change the return type accordingly to const_iterator:


template <class T> 
typename vector<T>::const_iterator  
vector_end(const vector<T>& myvector)
{
 return myvector.end();
}
vector<int> vi(5);
vector<int>::const_iterator itr=vector_end(vi);//now OK

You already know that the definition of itr can be simplified by using auto:


auto itr=vector_end(vi);

In a similar fashion, you want the return type of vector_end() to be deduced automatically from the expression myvector.end(). This is exactly what decltypedoes.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap