我担心这是一个愚蠢的问题,但......
有人可以建议我强制从函数(或方法)返回一个返回值,该值返回对内部静态变量或类/结构成员的引用 ,仅分配给引用变量?
我试着用一个简单的例子来解释我的愿望。
给定以下代码,使用返回对内部静态变量的引用的函数wrapValue()
int & wrapValue (int v0) { static int val; return val = v0; } int main () { // how to permit this ... int & v0 { wrapValue(0) }; // ... but forbid this ... int v1 { wrapValue(1) }; int v2; // ... and this ? v2 = wrapValue(2); }有一种方法可以允许初始化v0 (并将v0绑定到静态变量),并禁止初始化v1和赋值v2 (不将v1和v2绑定到静态变量)?
如果使用当前的C ++标准是不可能的,我担心,有人可以建议我另一种方式(但不是太复杂:我打算在我想保持简单的库中使用它)禁止无限制的赋值?
I fear it's a dumb question but...
Someone can suggest me a way to force that a return value from a function (or a method), that return a reference to an internal static variable or a member of the class/struct, is assigned only to reference variables ?
I try to explain what I desire with a minimal example.
Given the following code, with a function wrapValue() that return a reference to the internal static variable,
int & wrapValue (int v0) { static int val; return val = v0; } int main () { // how to permit this ... int & v0 { wrapValue(0) }; // ... but forbid this ... int v1 { wrapValue(1) }; int v2; // ... and this ? v2 = wrapValue(2); }there is a way to permit the initialization of v0 (and bound v0 to the static variable) and forbid the initialization of v1 and the assignment of v2 (without bounding v1 and v2 to the static variable) ?
And if it's impossible with the current C++ standard, as I fear, someone can suggest me an alternative way (but not too complex: I intend use it in a library that I want to maintain simple) to forbid an unbounded assignment ?
最满意答案
这个解决方案有点棘手,但它的工作原理(我认为)如你所料:
#include <iostream> struct int_wrapper { int value; int_wrapper &operator=(int value) { this->value = value; return *this; } operator int&() { return value; } operator int() { return value; } }; int_wrapper& wrapValue (int v0) { static int_wrapper val; return val = v0; } int main () { // how to permit this ... int & v0 = wrapValue(0); // ... but forbid this ... //int v1 { wrapValue(1) }; // call ambigious int v2; (void)v0; (void)v2; // ... and this ? //v2 = wrapValue(2); // call ambigious }[现场演示]
This solution is somewhat tricky but it works (I think) as you expect:
#include <iostream> struct int_wrapper { int value; int_wrapper &operator=(int value) { this->value = value; return *this; } operator int&() { return value; } operator int() { return value; } }; int_wrapper& wrapValue (int v0) { static int_wrapper val; return val = v0; } int main () { // how to permit this ... int & v0 = wrapValue(0); // ... but forbid this ... //int v1 { wrapValue(1) }; // call ambigious int v2; (void)v0; (void)v2; // ... and this ? //v2 = wrapValue(2); // call ambigious }[live demo]
更多推荐
发布评论