-3

Having trouble finding any resources on this.

struct Beta {
    int foo;
    int bar;
    Beta(int aFoo, int aBar) : foo(aFoo), bar(aBar) {}

    operator Alpha() const { return Alpha(foo, bar); }
}
struct Alpha {
    float foo;
    float bar;
    Alpha(float aFoo, float aBar) : foo(aFoo), bar(aBar) {}
}

And now I have:

vector<Beta> betas;
vector<Alpha> alphas;
transform(beta.begin(), beta.end(), back_inserter(alphas), &Beta.operator Alpha());

But this fails so I'm wondering the proper way to do it.

2 Answers2

1

The easiest and most readable solution is just to use a lambda. Below is a complete example:

#include <algorithm>

struct Alpha {
    float foo;
    float bar;
    Alpha(float aFoo, float aBar) : foo(aFoo), bar(aBar) {}
};

struct Beta {
    int foo;
    int bar;
    Beta(int aFoo, int aBar) : foo(aFoo), bar(aBar) {}

    operator Alpha() const { return Alpha(foo, bar); }
};

int main() {
    std::vector<Beta> betas;
    std::vector<Alpha> alphas;
    std::transform(betas.begin(), betas.end(), back_inserter(alphas), [](Beta b) { return Alpha(b); });
}

If you insist that you want to explicitly bind the operator instead, or just want to see what that syntax looks like, use this instead: For me with GCC and optimizations turned on, this yields exactly the same assembly output as the lambda version above:

using namespace std::placeholders; // For _1
std::transform(betas.begin(), betas.end(), back_inserter(alphas), std::bind(&Beta::operator Alpha, _1));
wjl
  • 7,519
  • 2
  • 32
  • 41
0

What you tried is not possible in C++. You can insert a layer of abstraction (Call a function that calls the operator), but someone's beaten me to that option. So let's look at Alpha knowing how to construct itself based on Beta instead.

struct Alpha
{
    ...
    // construct an Alpha from a Beta
    Alpha(const Beta& source) :
            foo(source.foo), bar(source.bar)
    {
    }
};

Now you can use std::vector::insert to construct Alphas from Betas.

alphas.insert(alphas.begin(), betas.begin(), betas.end());

Full code with test:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

struct Beta
{
    int foo;
    int bar;
    Beta(int aFoo, int aBar) :
            foo(aFoo), bar(aBar)
    {
    }
};

struct Alpha
{
    float foo;
    float bar;
    Alpha(float aFoo, float aBar) :
            foo(aFoo), bar(aBar)
    {
    }
    Alpha(const Beta& source) :
            foo(source.foo), bar(source.bar)
    {
    }

};

int main()
{
    vector<Beta> betas
    {
      { 1, 1 },
      { 2, 2 },
      { 3, 3 } 
    };

    vector<Alpha> alphas;
    alphas.insert(alphas.begin(), betas.begin(), betas.end());
    for (const Alpha & a : alphas)
    {
        std::cout << a.foo << ',' << a.bar << std::endl;
    }
}

Note that while simpler, this might not be a viable option. Alpha may not know of the existence of Beta.

user4581301
  • 33,082
  • 7
  • 33
  • 54