views:

66

answers:

2

Hi,

I'm trying to figure out the correct way of initializing a static container variable whose template value is a private inner class. Here's a toy example

#include <vector>

using namespace std;

template <class myType>
class Foo {
private:
    class Bar {
        int x;
    };

    static vector<Bar*> bars;
};

template <class myType>
vector<Bar*> Foo<myType>::bars; // error C2065: 'Bar' : undeclared identifier

I've also tried

...

template <class myType>
vector<Foo<myType>::Bar*> Foo<myType>::bars; // error C2059: syntax error : '>'

It works if class Bar is declared outside of class Foo but from a design standpoint this is an ugly solution. Any suggestions?

FYI, everything is declared in a .h file.

+8  A: 

Try this:

template <class myType>
vector<typename Foo<myType>::Bar*> Foo<myType>::bars;
Donotalo
Beat me by 4secs! `:+1` from me.
sbi
i always got beaten by large margin. :(
Donotalo
Yup, beat me too. The rule is, use keyword `typename` before A::B whenever it's supposed to be a type and expression A involves a template parameter.
aschepler
It works. Thanks! You guys are awesome. Now to google `typename` :-)
jok3rnaut
If anyone wants a good explanation of why C++ requires `typename` under the circumstances described by _aschepler_, see this site http://pages.cs.wisc.edu/~driscoll/typename.html
jok3rnaut
A: 

vector<Foo::Bar*> Foo<myType>::bars; ... note the Foo::

dgnorton
-1? ... please educate me.
dgnorton
@dgnorton: Have you tried compiling it? It fails on `gcc`. `Foo` needs to be qualified with the type parameter among other things.
Richard Cook
@Richard, on VS 2008 yes (no warnings)...on my way to compiling on gcc
dgnorton
@dgnorton: If you edit your answer I can unminusone you.
Richard Cook
@Richard, I'm not worried about rep. I'll leave my wrong answer here for everyone else's education. Still working on the gcc test.
dgnorton
@dgnorton: OK, cool. Thanks!
Richard Cook
@Richard, gcc didn't like it at all. Just leave it down voted (as it deserves to be) so that someone else using VS 2008 (VC9 compiler) might benefit.
dgnorton