我想用C++編寫一個類型定義,但不知道我想實現的東西是否合法。比方說,我想要做一個boost變體類型向量的typedef,它指向一個int或者另一個相同類型的向量。那麼,這是否合法?編譯器會抱怨嗎?C++中的遞歸Typedef
typedef std::vector<boost::variant<int *, boost::variant<int *, IntBranch*>> IntBranch;
我想用C++編寫一個類型定義,但不知道我想實現的東西是否合法。比方說,我想要做一個boost變體類型向量的typedef,它指向一個int或者另一個相同類型的向量。那麼,這是否合法?編譯器會抱怨嗎?C++中的遞歸Typedef
typedef std::vector<boost::variant<int *, boost::variant<int *, IntBranch*>> IntBranch;
您可以使用boost::make_recursive_variant
用於這一目的:
#include <boost/variant.hpp>
typedef boost::make_recursive_variant<
int*,
std::vector<boost::recursive_variant_>
>::type IntBranch;
這是你將如何使用它:
#include <vector>
int main()
{
typedef boost::make_recursive_variant<
int*,
std::vector<boost::recursive_variant_>
>::type IntBranch;
int x = 42;
IntBranch ib = &x;
std::vector<IntBranch> v;
v.push_back(ib);
IntBranch ib2 = v;
// ...
}
這裏是一個live example。
哇,我印象深刻。 – chris 2013-04-07 00:21:33
@chris:實際上'recursive_wrapper'允許更多的控制,但在這種情況下'make_recursive_variant'應該足夠了 – 2013-04-07 00:23:15
非常感謝你發佈這段代碼。不幸的是,我在理解如何遍歷這棵樹時遇到了一些問題。假設我有IntBranch,其中整數填充到位置i,然後在位置i處有另一個向量。如何通過輸入某種位置矢量來遍歷這樣的樹? – user1876508 2013-04-08 03:33:52
如果編譯器抱怨,你會知道你什麼時候嘗試,它會給你一個錯誤。 – chris 2013-04-07 00:10:46
編譯器不會抱怨,但這不會做你想做的事恐怕 – 2013-04-07 00:11:14
@AndyProwl,它不會給沒有看到IntBranch的錯誤?像[this](http://liveworkspace.org/code/htaz%240)? – chris 2013-04-07 00:11:47