Thursday, 4 September 2014

Vexing C++ template issue

This is a pretty well know difference between the Visual Studio C++ compiler and GCC.

I wanted something that can clone a vector of pointers so I created

    template< class ContainerType, class ElementType >
    ContainerType *copySTLContainerPtr(
        const ContainerType *rhs )
    {
        ContainerType *returnValue = new ContainerType;

        ContainerType::const_iterator i;
        for(i=rhs->begin();i!=rhs->end();i++)
        {
            returnValue->push_back( new ElementType(*i));
        }

        return returnValue;
    }

Now this compiled just fine in Devstudio but GCC complained that const_iterator effectively didn't exist - it said it expected a ; before 'i'

Turns out that to make this work you have to say this instead

     typename ContainerType::const_iterator i;

This is pretty well documented on stack overflow here  

In honesty I've had this problem before but it took a while to dredge my memory. While searching for this I also found a really neat page describing some quite obscure C++ features includes templated template parameters, pointer to members and other cool stuff you may not have seen. Check it out here if this is of interest.

No comments:

Post a Comment