[英]C++ How to overload the subscript operator and return a function
這個問題和我發的一樣。 但我沒有得到一個好的答案,現在我試着把它說清楚。 (我希望!!)
我有一個包含“鍵/值”對的列表(向量)。 鍵/值對的示例是“Pi = 3.14159”或“UserName = Bob”。 “值”可以是字符串、布爾值、整數、浮點數或雙精度數。 例如,我需要可以添加到列表中的每種數據類型的函數。
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.
我現在有很多代碼。 但我不知道如何重載下標 []。
Foo & operator[]( const char * pszKey ){
*this->????
}
Foo & operator[]( const char * pszKey) 應該讓我找到密鑰,在 function 里面應該讓我添加鍵/值或返回一個值。 我不知道如何使用下標運算符添加鍵/值或返回值。 我希望有人可以寫一個小代碼來幫助我理解並幫助我解決問題??
這是我現在擁有的一些代碼。
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(...);
下標運算符應返回您用於存儲浮點數、整數、字符串等的任何變體類型。
那個變體類型( 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
};
現在你可以這樣說:
float pi = my_collection["pi"];
my_collection["name"] = "Harry Potter";
我不明白為什么不只使用std::map<std::string, std::variant<...>>
並使用operator=
和變體構造函數進行賦值,使用std::get<>
獲取正確的值類型。 無論如何,這是一個包裝器,帶有您建議的請求接口:
#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.