Answer the question
In order to leave comments, you need to log in
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);
Answer the question
In order to leave comments, you need to log in
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);
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
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/
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);
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);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question