【问题标题】:Avoiding const/non-const duplication of method accepting a lambda避免接受 lambda 的方法的 const/non-const 重复
【发布时间】:2018-05-05 17:48:28
【问题描述】:

class Frame<P> 表示像素类型为P 的图像。由于底层数据缓冲区格式具有多种灵活性,因此遍历其像素的算法非常重要。

template <typename P, bool RM = true> // P is pixel type; RM = is_row_major
class Frame {

    // ...

    template<typename F>
    void iterate(F f) { // iterate in a way that is performant for this buffer
        if (stride == (RM ? size.w : size.h)) {
            auto n = size.area();
            for (index_t k = 0; k < n; k++) {
                f(view[k]);
            }
        }
        else {
            auto s = static_cast<index_t>(stride)*(RM ? size.h : size.w);
            for (index_t k0 = 0; k0 < s; k0 += stride) {
                auto m = k0 + (RM ? size.w : size.h);
                for (index_t k = k0; k < m; k++) {
                    f(view[k]);
                }
            }
        }
    }
}

我希望能够同时调用iterate(fc) constiterate(f)(分别使用lambda 签名fc(const P&amp;)f(P&amp;))。我可以复制整个函数体并将const 附加到签名中,但有更好的方法吗?

【问题讨论】:

  • 这里的thread 有帮助吗? (如果不是,那么我显然没有理解这个问题——你能把它说得更清楚一些,并可能最小化你的例子吗?)
  • @davidhigh 不确定。我经常在简单的吸气剂上使用它。在这里使用const_cast 也安全吗?
  • 用它做什么?坦率地说,我没有理解这个问题......你能否在你的问题中举例说明你想要做什么,只有两个 operator+= 成员,一个 const,一个非 const?
  • @davidhigh 对我来说operator+= 本质上是非常量的。我想要的是一个 iterateTogether() const 而不复制整个方法。
  • 为什么不能只拥有一个iterateTogether 函数,即const?从非常量函数调用const 成员函数没有问题。

标签: c++ c++11 lambda constants


【解决方案1】:

不能推导出成员函数的constness。但是,使用转发引用可以推断出函数参数的costness。因此,您可以只委托给一个以对象类型作为参数并转发所有其他参数的函数。这样重复的代码就变得微不足道了。如果函数需要访问 privateprotected 成员,您只需将其设为(可能是 privatestatic 成员:

template <typename T, bool PM = true>
class Frame {
    template <typename F1, typename F2>
    static void iterateTogether(F1&& f1, F2&& f2) {
        // actual implementation goes here
    }
public:
    template <typename F2>
    void iterateTogether(F2&& other){
        iterateTogether(*this, std::forward<F2>(other));
    }
    // ...
 };

上面使用的实现还允许参数的不同constness。如果您想将参数限制为真的只是 Frame 的一个特化,您需要限制函数,但这很容易做到。

我个人的偏好是无论如何都只有微不足道的成员,并将任何非微不足道的事情委托给通用算法。我的偏好是类只是保持它们的不变量,有趣的用途是通过算法实现的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    • 2018-08-29
    相关资源
    最近更新 更多