[英]Is there a way to store multiple types of struct members pointers
我有這段代碼,可以很好地按索引檢索foo
成員。
#include <string>
#include <iostream>
struct Foo {
int a = 42;
int b = 16;
std::string str = "hi";
};
int main()
{
int Foo::*members[] = { &Foo::a, &Foo::b };
Foo foo;
std::cout << foo.*members[1] << std::endl;
return 0;
}
問題是我的結構上有一個std::string
,我希望能夠以相同的方式訪問,是否有可擴展到任何類型的解決方案?
#include <string>
#include <iostream>
#include <any>
struct Foo {
int a = 42;
int b = 16;
std::string str = "coucou";
};
int main()
{
std::any Foo::*members[] = { (std::any Foo::*)&Foo::a, (std::any Foo::*)&Foo::b, (std::any Foo::*)&Foo::str };
Foo foo;
std::cout << std::any_cast<int>(foo.*members[0]) << std::endl;
return 0;
}
我告訴自己,如果存儲一個std::any
數組,那就行了。 事實上,這段代碼確實可以編譯但會崩潰。
任何解決方案?
您可以使用std::tuple
:
std::tuple members{&Foo::a, &Foo::b, &Foo::str }; // C++17 CTAD
// else, use `std::make_tuple`
Foo foo;
std::cout << foo.*std::get<0>(members) << " " << foo.*std::get<2>(members) << std::endl;
(我首先要說我同意@MarekR 的評論,你的問題可能是一個“XY 問題” ,你可能根本不想這樣做......但仍然:)
這是一個有趣的挑戰 - “瘋狂天才”安東尼 Polukhin 在他的magic_get庫中解決了這個挑戰 -前提是您使用的是 C++14 語言標准或更高版本。
實際上不需要存儲任何東西! 結構體定義本身具有您需要的所有信息。 因此,當你寫:
#include <iostream>
#include <string>
#include "boost/pfr.hpp" // <- Not formally a part of Boost, yet...
// you'll need to download the library from github
struct Foo {
int a = 42;
int b = 16;
std::string str = "hi";
};
int main() {
Foo my_foo;
std::cout
<< "a is " << boost::pfr::get<0>(my_foo) << ", "
<< "b is " << boost::pfr::get<1>(my_foo) << ", "
<< "and str is \"" << boost::pfr::get<2>(my_foo) << "\".\n";
}
你得到:
a is 42, b is 16, and str is "hi".
就像你想要的那樣。
要了解到底發生了什么,以及這種黑魔法的來源,請觀看安東尼 2018 年的演講:
盡量不要在 Struct 中使用string
作為指針,因為它不會指向任何內容。 相反,您可以像這樣簡單地使用:
std::cout << foo.str << std::endl;
它也會輸出你的字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.