c++ - 这是在 C++ 中执行 "with"语句的最佳方法吗?

标签 c++ c++11 with-statement

编辑:

所以这个问题被误解到如此荒谬的程度以至于它不再有意义了。我不知道如何,因为我实际上的问题是我的具体实现是否是——是的,众所周知,这是毫无意义的,是的,与惯用的 C++ 完全不同——宏已尽其所能,它是否必须使用 auto,或者是否有合适的解决方法。它不应该引起如此多的关注,当然也不应该产生如此严重的误解。要求受访者编辑他们的答案毫无意义,我不希望任何人因此而失去声誉,这里有一些很好的信息可供 future 潜在的观众使用,所以我将任意选择一个投票较低的人平均分配所涉及的声誉的答案。往前走,这里没什么可看的。


我看到了this question并决定用 C++ 编写 with 语句可能会很有趣。 auto 关键字让这件事变得非常简单,但是是否有更好的方法来做到这一点,或许不使用 auto?为简洁起见,我省略了部分代码。

template<class T>
struct with_helper {

    with_helper(T& v) : value(v), alive(true) {}

    T* operator->() { return &value; }
    T& operator*() { return value; }

    T& value;
    bool alive;

};


template<class T> struct with_helper<const T> { ... };


template<class T> with_helper<T>       make_with_helper(T& value) { ... }
template<class T> with_helper<const T> make_with_helper(const T& value) { ... }


#define with(value) \
for (auto o = make_with_helper(value); o.alive; o.alive = false)

这是一个(更新的)用法示例,其中包含一个更典型的案例,显示了 with 在其他语言中的用法。

int main(int argc, char** argv) {

    Object object;

    with (object) {

        o->member = 0;
        o->method(1);
        o->method(2);
        o->method(3);

    }

    with (object.get_property("foo").perform_task(1, 2, 3).result()) {

        std::cout
            << (*o)[0] << '\n'
            << (*o)[1] << '\n'
            << (*o)[2] << '\n';

    }

    return 0;

}

我选择 o 是因为它是一个不常见的标识符,而且它的形式给人一种“通用事物”的印象。如果您有更好的标识符或更有用的语法的想法,请提出建议。

最佳答案

如果您使用auto,为什么还要使用宏?

int main()
{
    std::vector<int> vector_with_uncommonly_long_identifier;

    {
        auto& o = vector_with_uncommonly_long_identifier;

        o.push_back(1);
        o.push_back(2);
        o.push_back(3);
    }

    const std::vector<int> constant_duplicate_of_vector_with_uncommonly_long_identifier
        (vector_with_uncommonly_long_identifier);

    {
        const auto& o = constant_duplicate_of_vector_with_uncommonly_long_identifier;

        std::cout
            << o[0] << '\n'
            << o[1] << '\n'
            << o[2] << '\n';
    }

    {
        auto o = constant_duplicate_of_vector_with_uncommonly_long_identifier.size();
        std::cout << o <<'\n';
    }
}

编辑:没有 auto,只需使用 typedef 和引用。

int main()
{
    typedef std::vector<int> Vec;

    Vec vector_with_uncommonly_long_identifier;

    {
        Vec& o = vector_with_uncommonly_long_identifier;

        o.push_back(1);
        o.push_back(2);
        o.push_back(3);
    }
}

关于c++ - 这是在 C++ 中执行 "with"语句的最佳方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4054946/

相关文章:

python - 跳过 -with- block 的执行

c++ - 检测卡片上的水滴并计算其数量和大小 OpenCV C++

c++ - 在 C++11 中对 vector 使用 for each

c++ - 关于一般网络编程中的write buffer

c++ - volatile 但不 protected 读取能否产生无限期的陈旧值? (在真实硬件上)

python - 是否可以在 python 中使用可选的 with/as 语句?

c++ - 在模板中实例化模板对象

c++ - 临时可修改适配器

C++ lambda 在模板的第二次扩展中没有捕获变量?

python - tf.variable_scope 中的重用选项如何工作?