简体   繁体   English

在没有 .get() 的情况下从结构返回成员

[英]Returning member from struct without .get()

Let's say I have following structure假设我有以下结构

template<typenameT>
class Foo
{
  T value;
  public:
    // some public logic
}

all what I want on this point is being able to say在这一点上我想要的就是能够说

Foo<int> A;

and then get value out of A as if it ware "just value of type T" and use it as follows然后从A获取值,就好像它“只是 T 类型的值”一样,并按如下方式使用它

int val1 = A;  // must correspond to int val1 = A.value
               // and
int& val2 = A; // must return reference of A.value and so on

I really don't want to user set/get because I am going to write such calls very often and want therefor simplify the code as much as possible.我真的不想用户设置/获取,因为我将经常编写此类调用并希望尽可能简化代码。

Firstly I thought overloading = might help, but I didn't get it right.首先,我认为重载 = 可能会有所帮助,但我没有做对。 It works for the opposite with the assignment operator such as Foo<int> A; int val = 1; A = val;它与赋值运算符相反,例如Foo<int> A; int val = 1; A = val; Foo<int> A; int val = 1; A = val;

EDIT: There is sure already answer on the web, but I couldn't find it under "assignment" keyword.编辑:网上肯定有答案,但我在“赋值”关键字下找不到它。

it seems you want to overload user-defined conversion operators:您似乎想重载用户定义的转换运算符:

template <typename T>
class Foo
{
  T value;
public:
    operator T () const { return value; }
    operator T& () { return value; }

    // some public logic
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM