I tried to specify just the constructor as the last argument of transform but it did not work since in C++ you can not take address of a constructor, but also signature would not match, constructor does not have return value.
I can easily wrap it in a lambda, but I wonder is there a simpler way to do this?
constructor functor does not look too bad, but it is not in std::, I would prefer some standard way of doing this(I looked into std::allocator<T>::construct, but signature does not match).
Here are my attempts:
#include <iostream>
#include <utility>
#include <iterator>
#include <algorithm>
#include <vector>
struct Square{
explicit Square(const int a):a(a){}
int a;
};
template<typename T>
struct constructor{
template<typename... Args>
T operator()(Args&&... args) {
return T(std::forward<Args>(args)...);
}
};
int main() {
std::vector<int> ints{1,2};
std::vector<Square> squares;
// :( can not take address of a constructor
//std::transform(ints.begin(), ints.end(), std::back_inserter(squares), &Square::Square);
// :/ works, but requires manual implementation of constructor
std::transform(ints.begin(), ints.end(), std::back_inserter(squares), constructor<Square>{});
// :/ works, but spammy
// std::transform(ints.begin(), ints.end(), std::back_inserter(squares), [](const int i) {return Square(i);});
for (const auto square:squares){
std::cout << square.a << std::endl;
}
}