Lately I have been learning dynamic memory allocation.
For practice purposes I tried to make a universal function that can accept iterators as parameters and then copies from beginning to end to a dynamically allocated array, then returns a pointer.
I want to make the function using complete deduction, without specifying return type when calling the function for example.
I would also like functions declaration to be as simple as possible, without any libraries (except std::remove_reference
from type_traits
if needed), IF possible.
The following code won't compile. And I know the code is useless from a logical view. I just wanted to show you my intentions and what I wanted to achieve...
#include <iostream>
#include <vector>
#include <type_traits>
template<typename T>
auto* returnPointer(T iter1, T iter2) -> std::remove_reference<decltype(*iter1)>::type
{
auto p = new std::remove_reference<decltype(*iter1)>::type [10];
auto p_help = p;
while(iter1 != iter2)
{
*p_help = *iter1;
p_help++;
iter1++;
}
return p;
}
int main ()
{
std::vector<int> v {0,1,2,3,4,5,6,7,8,9};
int *p = returnPointer(v.begin(), v.end());
for(int i = 0; i < 10; i++)
std::cout << p[i] << " ";
return 0;
}
I understand why it wont compile, what I cannot figure out how to make it work the way I imagined it...
Any help is very appreciated! :)