Sign in to follow this  

[C++] Syntax for unspecified template inside template definition

This topic is 3043 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi all, I don't come to compile a template definition which uses its unspecified template. When compiling C<T>, C alone is automatically replaced by C<T>. I don't see any logical issue in being able to use C as C<any T>, so probably I just need to know the right syntax. Here is some example code:
template <template <typename T> class B> struct A
{
  void func()
  {
    B<float> b;
  }
};

template <typename T> struct F
{
};

template <typename T> struct C
{
  void func()
  {
    A<F> af; // ok
    //A<C> ac; // invalid template argument for template parameter 'B', expected a class template
    //A<C<T> > at; // same error as above, and NOT what I want
    //A<C<typename> > act; // invalid template argument for template parameter 'B', expected a class template
    //A<template <typename T> C<T> > actt; // syntax error : ''template<''
  }
};

int main()
{
  C<int> c;
  c.func();
}

With Visual Studio 2005, the af declaration is "obviously" ok (not really needed in the example, just to show that analog things are working), ac is not. Thank you in advance!

Share this post


Link to post
Share on other sites
The problem is that the name "C" inside C::func() refers to the specific template instantiation at the point of call and not the uninstantiated template. Usually this is a useful feature of the language but here it's getting in your way.

A workaround:


template <template <typename T> class B> struct A
{
void func()
{
B<float> b;
}
};

template <typename T> struct F
{
};

template <typename T> struct C
{
void func();
};

template<typename T>
struct D : C<T> { }; // we give C another name...

template<typename T>
void C<T>::func()
{
A<D> ac; // ... and use that instead
}

int main()
{
C<int> c;
c.func();
}

Share this post


Link to post
Share on other sites
A nicer way:


// ...

template <typename T> struct C
{
void func()
{
A< ::C> ac;
}
};

// ...


I don't have a Windows machine to hand, but this is at least accepted by g++ 4.0.

Share this post


Link to post
Share on other sites

This topic is 3043 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this