Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 733
Thomas W. Avatar asked Nov 19 '14 09:11

Thomas W.


People also ask

Why do we use template template parameter?

8. Why we use :: template-template parameter? Explanation: It is used to adapt a policy into binary ones.

What is a template template parameter?

The first template parameter is the type of elements the container stores and the second template parameter is the defaulted allocator a container of the standard template library has. Even the allocator has a default value such as in the case of a std::vector. The allocator depends on the type of elements.

What is the usage of template in C++?

Templates in C++ is an interesting feature that is used for generic programming and templates in c++ is defined as a blueprint or formula for creating a generic class or a function. Simply put, you can create a single function or single class to work with different data types using templates.

Can template have default parameters?

Template parameters may have default arguments. The set of default template arguments accumulates over all declarations of a given template.


1 Answers

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;
}
like image 118
Piotr Skotnicki Avatar answered Oct 28 '22 06:10

Piotr Skotnicki