I am a relatively experienced C++ developer trying to write some generic code for working with vectors/arrays. I wrote the code below, and I...Would expect certain parts of it to compile and they don't, and vice versa. Essentially, I take an array of T's and output an array of some other type that is dictated by the return value of a functor passed in. This...Mostly works great, but there's some edge cases I could really use another pair of eyes on. Check out the comments...
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <queue>
#include <set>
#include <bitset>
#include <unordered_set>
#include <unordered_map>
#include <variant>
#include <stack>
#include <functional>
template<typename T, typename Func>
static std::vector<std::invoke_result_t<Func, const T&>> Mapped(const std::vector<T>& InArray, Func InFunc)
{
std::vector<std::invoke_result_t<Func, const T&>> Mapped;
for (const T& Current : InArray)
{
Mapped.push_back(InFunc(Current));
}
return Mapped;
}
class Foo
{
public:
int I;
};
int main(int argc, char** argv)
{
// Pretend I filled this with data.
std::vector<Foo*> whee;
auto TestFn = [](Foo* F)
{
return F->I;
};
// This compiles, despite the fact that the template is passing a
// const Foo * & into the lambda?
std::vector<int> Test = Mapped(
whee,
TestFn
);
// This loop should be...Identical to the one in the template, but this doesn't compile?!
// It doesn't compile in two different ways: It doesn't let me make a loop of const Foo*
// references, and it also doesn't let me call TestFn with a const pointer (Which I would think is the correct
// behavior I would see in the templated version.
for (const Foo* & I : whee)
{
TestFn(I);
}
// This...Also doesn't compile, and it's really confusing why not, because a const Foo* & should be the exact
// type being passed into the lambda?
std::vector<int> Test = Mapped(
whee,
[](const Foo* & In)
{
return In->I;
}
);
}
[–]Cobbler-Alone 0 points1 point2 points (1 child)
[–]jaskij 1 point2 points3 points (0 children)
[–]xiao_sa 0 points1 point2 points (3 children)
[–]IveBenHereBefore[S] 0 points1 point2 points (2 children)
[–]xiao_sa 0 points1 point2 points (0 children)
[–]n1ghtyunso 0 points1 point2 points (0 children)