0

Simply, can I pass std::vector as a template argument. Following example list usage

tempate<typename container_t, typename value_t>
struct container_types
{
  typedef container_t<value_t> value_container_t;
  typedef container_t<pair<value_t> pair_container_t;

};

I wish to pass container_types to generate final two data types. If this is not feasible, then how can I achieve the same.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
Kabira K
  • 1,916
  • 2
  • 22
  • 38
  • You *can* do it, but it's often not nearly as useful as you'd think. It's much better usually to pass in the actual types you want to use for your data members. – Kerrek SB Mar 13 '14 at 18:18
  • @juanchopanza: agreed that it is duplicate. – Kabira K Mar 13 '14 at 18:32
  • @Kerrek SB: possibly. but i go down this path and see how much trouble it creates. It would be useful in some scenarios. – Kabira K Mar 13 '14 at 18:33

1 Answers1

2

Yes, like this

#include <iostream>
#include <vector>

template <template<typename T> class container_t, typename value_t>
struct container_types
{
    typedef container_t<value_t> value_container_t;
    typedef container_t<std::pair<value_t,value_t > > pair_container_t;
};

template <typename T>
using my_vector = std::vector<T>;

int main(int argc,char** argv)
{
    container_types<my_vector,int>::value_container_t buff(100);
    std::cout << buff[50] << std::endl;
}

Note that I had to wrap std::vector with my_vector, as std::vector actually has several template arguments.

Ahmad Khan
  • 2,655
  • 19
  • 25
IdeaHat
  • 7,641
  • 1
  • 22
  • 53
  • To keep using std::vector directly [you can use variadic template](https://stackoverflow.com/a/21569318/51386). – yves Jan 04 '18 at 21:46