如何禁止赋值给不引用变量? [英] how to forbid assignment to not reference variables?

查看:92
本文介绍了如何禁止赋值给不引用变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我担心这是一个愚蠢的问题,但是...

I fear it's a dumb question but...

有人可以向我建议一种强制从函数(或方法)返回值的方法,返回对内部静态变量或类/结构成员的引用,仅分配给 reference 变量?

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 ?

我尝试解释一下

给出以下代码,并返回一个函数 wrapValue()引用内部静态变量

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);
 }

有一种方法可以初始化 v0 (并将 v0 绑定到静态变量),并禁止初始化 v1 v2 的赋值(不限制 v1 v2 到静态变量)?

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) ?

如果我担心,如果当前的C ++标准无法实现,有人可以建议我另一种方法(但不要太复杂:我打算使用它)在我想保持简单的库中)以禁止无限制的分配?

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 ?

推荐答案

此解决方案有些棘手,但可以解决(我想)如您所愿:

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
}

[实时演示]

这篇关于如何禁止赋值给不引用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆