c++ - 避免使用 auto 关键字字面上重复 const 和非常量的代码?

标签 c++ c++14

好的,我做了一些研究,显然在这个主题上有很多重复的问题,仅举几例:

等但我还是忍不住再次提出来,因为

  1. auto 类型的返回值,我实际上是在复制函数体,唯一的区别是 const 函数限定符。
  2. const 版本和非const 版本可能会返回彼此完全不兼容的类型。在这种情况下,Scott Meyers 的 const_cast 惯用语和“返回非 const 的私有(private) const 函数”技术都不起作用。

举个例子:

struct A {
    std::vector<int> examples;
    auto get() { return examples.begin(); }
    auto get() const { return examples.begin(); }
};  // Do I really have to duplicate?
    // My real-world code is much longer
    // and there are a lot of such get()'s

在这种特殊情况下,auto get() 返回一个 iteratorauto get() const 返回一个 const_iterator,并且两者不能相互转换(我知道 erase(it,it) 技巧在这种情况下进行转换,但这不是重点)。 const_cast 因此不起作用;即使它有效,也需要程序员手动推断 auto 类型,完全违背了使用 auto 的目的。

那么除了宏就真的没有办法了吗?

最佳答案

好的,经过一番修改后,我想出了以下两个解决方案,它们允许您保留自动返回类型并且只实现一次 getter。它使用与 Meyer 所做的相反的转换。

C++ 11/14

此版本仅在实现的函数中返回两个版本,或者使用 cbegin()或者如果你没有适合你的类型,这应该可以替代 cbegin() : return static_cast<const A&>(*this).examples.begin();基本上转换为常量并使用正常的 begin()获取常量的函数。

// Return both, and grab the required one
struct A
{
private:
    // This function does the actual getter work, hiding the template details
    // from the public interface, and allowing the use of auto as a return type
    auto get_do_work()
    {
        // Your getter logic etc.
        // ...
        // ...

        // Return both versions, but have the other functions extract the required one
        return std::make_pair(examples.begin(), examples.cbegin());
    }

public:
    std::vector<int> examples{ 0, 1, 2, 3, 4, 5 };

    // You'll get a regular iterator from the .first
    auto get()
    {
        return get_do_work().first;
    }

    // This will get a const iterator
    auto get() const
    {
        // Force using the non-const to get a const version here
        // Basically the inverse of Meyer's casting. Then just get
        // the const version of the type and return it
        return const_cast<A&>(*this).get_do_work().second;
    }

};

C++ 17 - 用 if constexpr 替代

这个应该更好,因为它只返回一个值,并且在编译时知道获得了哪个值,所以 auto会知道该怎么做。否则 get()功能基本相同。

// With if constexpr
struct A
{
private:
    // This function does the actual getter work, hiding the template details
    // from the public interface, and allowing the use of auto as a return type
    template<bool asConst>
    auto get_do_work()
    {
        // Your getter logic etc.
        // ...
        // ...

        if constexpr (asConst)
        {
            return examples.cbegin();

            // Alternatively
            // return static_cast<const A&>(*this).examples.begin();
        }
        else
        {
            return examples.begin();
        }
    }

public:
    std::vector<int> examples{ 0, 1, 2, 3, 4, 5 };

    // Nothing special here, you'll get a regular iterator
    auto get()
    {
        return get_do_work<false>();
    }

    // This will get a const iterator
    auto get() const
    {
        // Force using the non-const to get a const version here
        // Basically the inverse of Meyer's casting, except you get a
        // const_iterator as a result, so no logical difference to users
        return const_cast<A&>(*this).get_do_work<true>();
    }
};

这可能适用于您的自定义类型,也可能不适用于您的自定义类型,但它对我有用,并且它解决了代码重复的需要,尽管它使用了辅助函数。但反过来,实际的 setter/getter 变成了一行,所以这应该是合理的。

以下主要功能用于测试这两个解决方案,并按预期工作:

int main()
{    
    const A a;
    *a.get() += 1; // This is an error since it returns const_iterator

    A b;
    *b.get() += 1; // This works fine

    std::cout << *a.get() << "\n";
    std::cout << *b.get() << "\n";

    return 0;
}

关于c++ - 避免使用 auto 关键字字面上重复 const 和非常量的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49390454/

相关文章:

c++ - map可以包含类对象还是类对象?

c++ - MFC 获取文件夹

c++ - 传递大括号初始化器列表参数时调用可变参数函数模板的问题

c++ - 为什么 C++ 编译器不在下一行输出文本,而在其间放置空格时却输出文本?

c++ - 实现用于生成具有给定范围的索引序列的 C++ 模板

c++ - std::unique_ptr 和 std::shared_ptr 之间破坏行为差异的基本原理是什么?

c++ - 是否使用静态 constexpr 变量 odr?

c++计算编译时间常数,同时防止整数常数溢出

c++ - 用户定义类型的 std::common_type 特征

c++ - 使用 Boost.Hana 定义编译时 Comparable 对象