Returning a pointer from a template function with iterator parameters
I have been looking into dynamic memory allocation lately.
For practical purposes, I tried to create a generic function that can take iterators as parameters and then copy from beginning to end into a dynamically allocated array and then return a pointer.
I want the function to use full output, without specifying the return type when calling the function, eg.
I would also like to keep the function declarations as simple as possible, without any libraries (other than std::remove_reference
from type_traits
if needed) possibly possibly.
The following code will not compile. And I know the code is useless from the boolean 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 this won't compile, that I can't figure out how to make it work the way I imagined it ...
Any help is greatly appreciated! :)
source to share
- When using a return type declaration, you must use
auto
directly; - you need to add
typename
forstd::remove_reference<...>::type
or usestd::remove_reference_t
(since C ++ 14);
Then
auto returnPointer(T iter1, T iter2) -> typename std::remove_reference<decltype(*iter1)>::type*
// ~ ~~~~~~~~ ~
Other offers:
-
Since C ++ 14, you can take advantage of return type inference. so just
template<typename T> auto returnPointer(T iter1, T iter2) { auto p = new std::remove_reference_t<decltype(*iter1)> [10]; ... return p; // return type will be deduced from p }
-
You can use
std::distance
to get the number of items likeauto p = new std::remove_reference_t<decltype(*iter1)> [std::distance(iter1, iter2)];
-
Don't forget the
delete[]
pointer, i.e.delete[] p;
source to share