View Single Post
Old Aug 20th, 2007, 6:19 PM   #1
Jessehk
The Oblivious One
 
Jessehk's Avatar
 
Join Date: May 2005
Location: Ontario, Canada
Posts: 644
Rep Power: 4 Jessehk is on a distinguished road
The STL is really neat

http://www.sgi.com/tech/stl/table_of_contents.html

I don't know why I never realized it before, but the STL is really, really neat. The STL idea of concepts combined with boost::concept_traits allows you to check that template parameters pass certain requirements.

Example:
#include <iostream>
#include <vector>

#include <boost/concept_check.hpp>


template <typename InputIterator>
void display( InputIterator begin, InputIterator end ) {
    using namespace boost;
    
    function_requires<InputIteratorConcept<InputIterator> >();
    
    for (; begin != end; begin++ )
        std::cout << *begin;
    
    std::cout << std::endl;
}

int main() {
    std::vector<int> numbs;
    
    for ( int x = 0; x < 10; x++ )
        numbs.push_back( x );
    
    display( numbs.begin(), numbs.end() );
}

If I've done that right, it will only compile if the type of iterator passed to the display() function complies by the Input Iterator concept defined by the STL.

Here's another example:
template <typename Integer>
bool isEven( Integer n ) {
    using namespace boost;
    
    function_requires<IntegerConcept<Integer> >();
    
    return !(n & 1);
}

int main() {
    std::cout << isEven( 314 ) << std::endl; // Is fine --> concept check passes
    std::cout << isEven( 4.2 ) << std::endl; // BAD --> compile error
}

C++ continues to astound me with what it's capable of. :eek:
__________________
Dr. Zoidberg: [ecstatic] I'm going to a movie... with FRIENDS!
Jessehk is offline   Reply With Quote