D
D
datalink2012-12-20 14:47:16
C++ / C#
datalink, 2012-12-20 14:47:16

C++. Creating and initializing an arbitrary std container via template?

I write bikes

template<typename SomeContainer, typename T, size_t n>
SomeContainer ContainerMake(const T(&array)[n])
{
   return SomeContainer(array, array + n);
}

const int vals1[] = { 0, 1, 2, 3, 4};

vector<int> vct1 = ContainerMake<vector<int> >(vals1);

How to get rid of the explicit specification of int when calling ContainerMake?

Answer the question

In order to leave comments, you need to log in

6 answer(s)
C
CleverMouse, 2012-12-20
@CleverMouse

If you want to leave vector, and remove only int, then you don’t even need an additional class. However, keep in mind that std::vector actually has two template parameters.

template<template<typename U, typename Allocator> class Container, typename T, size_t n>
Container<T, allocator<T> > ContainerMake(const T(&array)[n])
{
  return Container<T, allocator<T> >(array, array + n);
}

const int vals1[] = {0, 1, 2, 3, 4};
vector<int> vct1 = ContainerMake<vector>(vals1);

D
Dmitry, 2012-12-22
@EvilsInterrupt

1) Or it seems to me or actually you are trying to make container-independent code? If yes, then throw this idea out of your head
2) Somehow not in English: “ContainerMake”. My options are 1) ContainerMaker or 2) makeContainer

T
Talyutin, 2012-12-20
@Talyutin

What exactly do you want to get, maybe write more examples of the code that you want to call to convert.
In your current specific case, you can pass vec1 by reference to ContainerMake. Then add a couple of template parameters for the method and everything will be fine.
In general, of course, you can pile up using template specializations (but this is for structures, i.e. they will be like factories) http://habrahabr.ru/post/54762/

C
CleverMouse, 2012-12-20
@CleverMouse

Get a helper class, return it from ContainerMake and do the main work in a cast operator:

template<typename T, size_t n>
class MakerContainer
{
  const T* Array;
public:
  MakerContainer(const T* array) : Array(array) {}
  template<typename U>
  operator U() const
  { return U(Array, Array + n); }
};

template<typename T, size_t n>
MakerContainer<T,n> ContainerMake(const T(&array)[n])
{
  return MakerContainer<T,n>(array);
}

const int vals1[] = {0, 1, 2, 3, 4};
vector<int> vct1 = ContainerMake(vals1);

A
antonyter, 2012-12-20
@antonyter

Maybe easier?

template<typename SomeContainer,typename T, size_t n>
void ContainerMake(SomeContainer A, const T(&array)[n])
{
   A = SomeContainer(array, array + n);
}

const int vals1[] = { 0, 1, 2, 3, 4};

vector<int> vct1;
ContainerMake(vct1, vals1);

G
Gribozavr, 2012-12-23
@gribozavr

Just use uniform initialization in C++11. Today there is no reason not to use C++11.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question