编辑:
所以这个问题被误解为这样一个荒谬的程度,它已经没有意义了.我不知道怎么回事,因为我实际问过的问题是我是否具体实现了这个 - 是的,已知是无意义的,是的,不是非常类似于惯用的C++ - 宏,它是否尽可能好,以及它是否必然不得不使用auto,或者如果有合适的解决方法.它不应该产生这么多的关注,当然不是对这种程度的误解.要求受访者编辑他们的答案是毫无意义的,我不希望任何人因此而失去声誉,并且在这里有一些好的信息可供潜在的未来观众使用,所以我将随意挑选一个较低的选民答案是均匀分配所涉及的声誉.继续前进,没有什么可看的.
我看到了这个问题,并认为with用C++ 编写语句可能很有趣.该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) …Run Code Online (Sandbox Code Playgroud) struct Heap {
int capacity;
int heapSize;
int *tree; // the heap binary tree
int *pos; // pos[i] is the position of values[i] in items
float *p; // priority value of each heap element
};
void initHeap(struct Heap *heap, int capacity) {
heap->capacity = capacity;
heap->heapSize = 0;
heap->tree = malloc(sizeof(int)*(capacity+1));
heap->pos = malloc(sizeof(int)*(capacity+1));
heap->p = malloc(sizeof(float)*(capacity+1));
}
void betterInit(struct Heap *heap, int capacity) {
with (heap) { // doesn't exist
capacity = capacity;
heapSize = 0;
tree = malloc(sizeof(int)*(capacity+1)); …Run Code Online (Sandbox Code Playgroud)