简体   繁体   English

C++ 如何重载下标运算符并返回一个 function

[英]C++ How to overload the subscript operator and return a function

This question is same as i post.这个问题和我发的一样。 but i not get a good answer and now i try to make it much clear.但我没有得到一个好的答案,现在我试着把它说清楚。 (i hope!!) (我希望!!)

I have a list (vector) that will hold 'key/value' pairs.我有一个包含“键/值”对的列表(向量)。 Example of key/value pair is "Pi = 3.14159" or "UserName = Bob".键/值对的示例是“Pi = 3.14159”或“UserName = Bob”。 The 'Value's can be string, bool, int, float, or doubles. “值”可以是字符串、布尔值、整数、浮点数或双精度数。 I need functions for each data type that i can add to the list, for example.例如,我需要可以添加到列表中的每种数据类型的函数。

Foo f; f["Pi"].SetFloat(3.14159);          <--- Add float key/value
Foo f; float myFloat = f["Pi"].GetFloat(); <--- Get float value
          or
Foo f; f["UserName"].SetStr("Bob");        <-- Add string key/value
Foo f; const char * name = f["UserName"].GetStr(); < -- Get String.

I have much of the code now.我现在有很多代码。 BUT i do not know how to overload the subscript [].但我不知道如何重载下标 []。

Foo & operator[]( const char * pszKey ){
   *this->????
 }  

The Foo & operator[]( const char * pszKey) should let me find the Key and inside the function should let me add key/value or return a value. Foo & operator[]( const char * pszKey) 应该让我找到密钥,在 function 里面应该让我添加键/值或返回一个值。 I do not know how to add key/value or return the value useing the subscript operator.我不知道如何使用下标运算符添加键/值或返回值。 I hope someone can write a small code to help me understand and help me with is question??我希望有人可以写一个小代码来帮助我理解并帮助我解决问题??

This is some of my code i have now.这是我现在拥有的一些代码。

const char * va( const char * fmt, ... ) { // va = "VarArgs"
  // Format a value into a string.
 }

void Foo::SetString( const char * Key, const char * ) { // Private
   // Add 'key' and 'value' to a vector as a pair.
 }

const char * Foo::GetString( const char * key ) {  // Private
   // Look up 'key' from the vector and return the 'value'.
 }

...

const char * Foo::GetStr( const * Key ) {
  ...
 }
void Foo::SetStr( const char * Key, const int Value ) {
   SetStr( Key, va("%i", Value ));
 }

float Foo::GetFloat( const char * Key ) {
   return (float) atof( GetStr( Key ));
 }
void Foo::SetFloat( const char * Key ) {
  ....
 }  

void Foo::SetInt( .... ) ;
const int * Foo::GetInt(...);

void Foo::SetBool( ... ); 
const bool Foo::GetBool(...);

The subscript operator should return whatever variant type you are using to store the float, int, string, etc.下标运算符应返回您用于存储浮点数、整数、字符串等的任何变体类型。

And that variant type ( Foo , is it?) should have assignment and conversion operators:那个变体类型( Foo ,是吗?)应该有赋值和转换运算符:

struct my_variant_type
{
  ...

  operator int   () const { return GetInt(); }
  operator float () const { return GetFloat(); }
  operator string() const { return GetStr(); }
  etc

  my_variant_type & operator = ( int n ) { SetInt( n ); return *this; }
  my_variant_type & operator = ( float f ) { SetFloat( f ); return *this; }
  my_variant_type & operator = ( const std::string & s ) { SetStr( s ); return *this; }
  etc
};

Now you can say things like:现在你可以这样说:

float pi = my_collection["pi"];
my_collection["name"] = "Harry Potter";

I do not understand exactly why not just use std::map<std::string, std::variant<...>> and use operator= with variant constructor for assignment and std::get<> for getting value of proper type.我不明白为什么不只使用std::map<std::string, std::variant<...>>并使用operator=和变体构造函数进行赋值,使用std::get<>获取正确的值类型。 Anyway, here's a wrapper around with requested interface that you proposed:无论如何,这是一个包装器,带有您建议的请求接口:

#include <variant>
#include <string>
#include <map>

struct Foo {
    using Value = std::variant<
        std::string,
        bool,
        int,
        float,
        double>;
    std::map<std::string, Value> data;

    struct YourInterface {
        Value& v;
        float GetFloat() {
            return std::get<float>(v);
        }
        void SetFloat(float f) {
            v = Value(f);
        }
        void SetStr(std::string n) {
            v = Value(n);
        }
        std::string GetStr() {
            return std::get<std::string>(v);
        }
        // etc.
    };
    YourInterface operator[](const char *pszKey) {
        return FooInterface(data[pszKey]);
    }
};

int main() {
    Foo f;
    f["UserName"].SetStr("Bob");
    float myFloat = f["Pi"].GetFloat();
    f["UserName"].SetStr("Bob");
    std::string name = f["UserName"].GetStr();
}

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

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