Login | Register   
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
 

Template Constraints Are So 1997; Usher in C++09 Concepts-2 : Page 2

Puzzled by indecipherable template compilation errors? Still struggling in vein to enforce restrictions on template parameters? It's time you migrated C++09 concepts!


advertisement

Sort It Out
Consider the following example of a perfectly valid program:


#include <vector>
#include <algorithm>
using namespace std;

struct C {
  void f();
};

int main()
{
 vector <C> vc;
 vb.push_back(C());
 vb.push_back(C());
}

This code is fine. However, when you add the following line to your program:




sort(vb.begin(), vb.end());//error

Your compiler barks at you:


[C++ Error] algorith.h(644): E2093 'operator<' 
not implemented in type 'C' for arguments of the same type.

The diagnostic doesn't really explain what the problem is. std::sort() has a usage constraint which isn't stated overtly in its declaration: "C shall be a type that has a less-than operator taking references to two references to C and returning bool".

In many other instances of violating an implicit template constraint you won't even get a compilation error; your program will simply have undefined behavior. Take, for example, auto_ptr. Standard Library containers have an implicit requirement that their objects shall be copy-constructible and assignable. auto_ptr is neither of these. Lo and behold, the instantiations of vector<auto_ptr> and deque<auto_ptr>compile successfully:


vector <auto_ptr<int> > va; //undefined behavior
deque <auto_ptr<int> > da;//undefined behavior

In this case, the implicit requirement that auto_ptr<int> shall be copy-constructible and assignable isn't enforced at compile time. It isn't expressed in the declarations of vector and dequeeither.

Generally speaking, the problem is that C++03 doesn't have a mechanism for expressing template constraints consistently and clearly.



Comment and Contribute

 

 

 

 

 


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

 

 

Sitemap