c++syntaxquantitative-financecomputational-finance

Coding iterator function for STL Class


I am working through some C++ code from "Financial Instrument Pricing Using C++" - a book on option pricing using C++. Following code is a small snippet stripped of many details which basically attempts to define a SimplePropertySet class that is intended to contain a name and list.

#include <iostream>
#include <list>
using namespace::std;

template <class N, class V> class SimplePropertySet
{
    private:
    N name;     // The name of the set
    list<V> sl;

    public:
    typedef typename list<V>::iterator iterator;
    typedef typename list<V>::const_iterator const_iterator;

    SimplePropertySet();        // Default constructor
    virtual ~SimplePropertySet();   // Destructor

    iterator Begin();           // Return iterator at begin of composite
    const_iterator Begin() const;// Return const iterator at begin of composite
};
template <class N, class V>
SimplePropertySet<N,V>::SimplePropertySet()
{ //Default Constructor
}

template <class N, class V>
SimplePropertySet<N,V>::~SimplePropertySet()
{ // Destructor
}
// Iterator functions
template <class N, class V>
SimplePropertySet<N,V>::iterator SimplePropertySet<N,V>::Begin()//<--this line gives error
{ // Return iterator at begin of composite
    return sl.begin();
}

int main(){
    return(0);//Just a dummy line to see if the code would compile
}

On compiling this code on VS2008, I obtain the following errors:

warning C4346: 'SimplePropertySet::iterator' : dependent name is not a type
    prefix with 'typename' to indicate a type
error C2143: syntax error : missing ';' before 'SimplePropertySet::Begin'
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

Is there something stupid or basic that I am getting wrong or forgetting here? Is it a syntax error? I am unable to put my finger on it. The book from which this code snippet is taken says their code was compiled on Visual Studio 6. Is this some version-related issue?

Thanks.


Solution

  • As indicated by the compiler, you must replace :

    template <class N, class V>
    SimplePropertySet<N,V>::iterator SimplePropertySet<N,V>::Begin()
    

    with :

    template <class N, class V>
    typename SimplePropertySet<N,V>::iterator SimplePropertySet<N,V>::Begin()
    

    See this link for an explanation on dependent names.