Search code examples
c++templatestypedeftypenameclass-constructors

C++ templated class and init in constructor


I have a templated class, Foo :

template <class A, class B>
class Foo
{
public:
    Foo(A &aInstance);

private:
    Attr<Foo> _attr;
};

Then I have another templated class called Attr which is an attribute of my Foo class and which takes as template parameter the Foo class itself.

template <class C>
class Attr
{
    class SomeType
    {
        SomeType();
        ~SomeType();
    };

    Attr(const SomeType* st);
    ~Attr();

private:
    Attr();
}

I want to init _attr (of type Attr) in the constructor, casting the first parameter from the template as SomeType.

Foo constructor implementation :

template<class A, class B>
Foo<A, B>::Foo(A &aInstance):
    _attr(
        (Attr<Foo<A, B> >::SomeType *) aInstance)
{

}

This won't compile :

error: expected primary-expression before ')' token

That error refers to the cast line in the Foo contructor implementation, as if SomeType was not recognized.

I now have an instance, but still got the same error.


Solution

  • 0)

    (Attr<Foo<A, B> >::SomeType *) A)
    

    at that point, A is a typename, i.e. the name of a type, thus, not anything you can cast.

    1)

    Also, Foo<A,B> is dependent upon A and B, therefore, Attr<Foo<A, B> > is a dependent name, too. Hence, you need a typename there so as to tell the compiler that SomeType is a type:

    (typename Attr<Foo<A, B> >::SomeType *) somePointer)
    

    2)

    Furthermore, in C++, generally prefer C++-casts over C-style-casts. You'll catch a lot of mistakes with them. See also this tutorial :)

    3)

    On the other hand: Are you sure you need the cast by design, or should Attr point to exactly a Foo<A, B>?