【问题标题】:Can I generate templates based on opeators? [duplicate]可以根据算子生成模板吗? [复制]
【发布时间】:2022-01-10 21:15:52
【问题描述】:

我想知道是否可以使用模板为操作员创建通用代码。考虑一个简化的示例,该示例演示了我正在尝试做的事情。

template<operator O>
int do_thing(int a, int b) {
  return a O b;
}

int main() {
  // expected to return 10
  int foo = do_thing<operator+>(7, 3);

  // expected to return 4
  int bar = do_thing<operator->(7, 3);

  return 0;
}

我能表达出这样的话吗?我有几个相同的功能,除非它们之间有一个不同的操作,我觉得必须有一种方法可以更清晰地表达。

【问题讨论】:

标签: c++ templates operators


【解决方案1】:

你不能使用“operator+”作为模板参数,但你可以这样做:

#include <iostream>

// do_thing
template<typename operator_t, typename type_t>
auto do_thing(const type_t& a, const type_t& b)
{
    // create temp inst
    return operator_t::op(a, b);
}

// template for operator
template<typename type_t>
struct plus_t
{
    static auto op(const type_t& a, const type_t& b)
    {
        return a + b;
    }
};

int main()
{
    // specialize operator for int
    using plus = plus_t<int>;

    // do your thing
    auto value = do_thing<plus>(2, 3);
    std::cout << "result of do_thing<plus>(2,3) = " << value << "\n";

    return 0;
}

【讨论】:

  • 我建议改为auto operator()(const type_t&amp; a, const type_t&amp; b),然后是return operator_t{}(a, b);。这样它对标准的函数运算符类型也很有用。
  • 当我有那个,决定去这个建议使它更具可读性。我认为临时的创建会令人困惑:) 但是我同意
猜你喜欢
  • 1970-01-01
  • 2021-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-01
  • 1970-01-01
  • 2012-06-05
相关资源
最近更新 更多