Search code examples
c++templatestemplate-templates

Correct usage of C++ template template parameters


I've some trouble to make use of template template parameters. Here is a very simplified example:

template <typename T> 
struct Foo {
  T t;
};

template <template <class X> class T>
struct Bar {
  T<X> data;
  X x;
};

int main()
{
  Bar<Foo<int>> a;
}

The compiler (g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2) reports the following error:

main.cpp:8:5: error: ‘X’ was not declared in this scope
   T<X> data;
     ^

main.cpp:8:6: error: template argument 1 is invalid
   T<X> data;
      ^

Any idea what's wrong?


Solution

  • So I would like so make use of something like Bar<Foo<>>

    template <typename T = int> 
    struct Foo {
      T t;
    };
    
    template <typename T>
    struct Baz {
      T t;
    };
    
    template <typename T>
    struct Bar;
    
    template <template <typename> class T, typename X>
    struct Bar<T<X>> {
      T<X> data;
      X x;
    };
    
    int main()
    {
      Bar<Foo<>> a;
      Bar<Baz<float>> b;
    }