编辑:
所以这个问题被误解到如此荒谬的程度,以至于它不再有意义。我不知道如何,因为我实际问的问题是我对这个宏的具体实现——是的,众所周知,毫无意义,是的,与惯用的 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
是因为它是一个不常见的标识符,它的形式给人一种“通用事物”的印象。如果您有更好的标识符或更有用的语法的想法,那么请提出建议。 最佳答案
??尝试将 vb 语法转换为 C++with
表示默认情况下执行以下块中的所有操作,引用我所说的对象,对吗? Executes a series of statements making repeated reference to a single object or structure.
with(a)
.do
.domore
.doitall
那么该示例如何为您提供相同的语法?
对我来说为什么要使用 with where multiple de referencess 的例子
所以而不是
book.sheet.table.col(a).row(2).setColour
book.sheet.table.col(a).row(2).setFont
book.sheet.table.col(a).row(2).setText
book.sheet.table.col(a).row(2).setBorder
你有
with( book.sheet.table.col(a).row(2) )
.setColour
.setFont
.setText
.setBorder
C++ 中的语法似乎同样简单、更常见
cell& c = book.sheet.table.col(a).row(2);
c.setColour
c.setFont
c.setText
c.setBorder
关于c++ - 这是在 C++ 中执行 "with"语句的最佳方法吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4054946/