【问题标题】:C++ Passing Operator as ParameterC++ 将运算符作为参数传递
【发布时间】:2017-11-18 14:16:45
【问题描述】:

在这方面找不到任何资源。

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) {}
}

现在我有了:

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

但这失败了,所以我想知道正确的方法。

【问题讨论】:

  • 不,我是倒着读的。我很抱歉。
  • 请确认目标:将betas复制到alphas?没什么好看的?
  • 虽然我认为 OP 试图做的事情是不可能的,但我相信他们想做的事情值得解锁和回答......如果他们清理了问题。
  • @user4581301 给你,

标签: c++


【解决方案1】:

最简单且最易读的解决方案就是使用 lambda。下面是一个完整的例子:

#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); });
}

如果您坚持要显式绑定运算符,或者只是想看看该语法是什么样的,请改用这个:对我来说,打开 GCC 和优化,这会产生完全正确与上面的 lambda 版本相同的汇编输出:

using namespace std::placeholders; // For _1
std::transform(betas.begin(), betas.end(), back_inserter(alphas), std::bind(&Beta::operator Alpha, _1));

【讨论】:

  • 谢谢我知道第一个,有点想知道语法是什么样的。非常感谢您的出色回答。
【解决方案2】:

您所尝试的在 C++ 中是不可能的。您可以插入一个抽象层(调用一个调用运算符的函数),但有人在这个选项上打败了我。那么让我们看看Alpha知道如何基于Beta来构建自己。

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

现在您可以通过use std::vector::insertBetas 构造Alphas。

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

带测试的完整代码:

#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;
    }
}

请注意,虽然更简单,但这可能不是一个可行的选择。 Alpha 可能不知道 Beta 的存在。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 2014-07-24
    相关资源
    最近更新 更多