I need to write a class template definition with two template parameters (type , functor) and two template arguments (array/std::vector , int) that can execute the following code:
const char* message= "Message";
const transform<char, firstFunctor> first(message, lengthOfMessage);
transform_view<int, secondFunctor> second(intArray, intSize);
transform<double, thirdFunctor> third(doubleArray, doubleSize);
The type of the array/ vector has to match the type of the first template parameter.
I tried some variations like this:
template <typename A, typename B>
class transform
{
public:
transform<A, B>(A[], B) {...};
}
But I could not get the constructor's first parameter to match all of the three types.
Any advice is appreciated, thanks!
you wrote the definition of the constructor incorrectly.
transform<A, B>(A[], B) {...};
you will pass a vector, so why did you write A[]
as a parameter type?
You need something like the following
#include <iostream>
template <typename T>
struct functor{
void operator()(const T array [], size_t sze) {
for (int i{}; i < sze; ++i) {
std::cout << array[i] << " ";
}
std::cout << "\n";
}
};
template<typename T, typename Function>
class transform {
const T* array;
size_t sze;
Function functor{};
public:
transform(const T array [], size_t sze):array{array}, sze{sze}{
functor(array, sze);
}
};
template< typename T, typename E>
using transform_view = transform<T, E>;
int main()
{
using firstFunctor = functor<char>;
using secondFunctor = functor<int>;
using thirdFunctor = functor<double>;
const char *message = "Message";
size_t lengthOfMessage = 7;
int intArray[] = {1, 3};
size_t intSize = 2;
double doubleArray[] = {1.4, 3.2};
size_t doubleSize = 2;
//The given three lines
const transform<char, firstFunctor> first(message, lengthOfMessage);
transform_view<int, secondFunctor> second(intArray, intSize);
transform<double, thirdFunctor> third(doubleArray, doubleSize);
}
The output
M e s s a g e
1 3
1.4 3.2