1
我有一個函數簽名,它以vector<specific_type>
作爲參數並調用另一個函數,它具有vector<boost::variant<specific_type, ...>>
作爲參數。一個簡單的參數轉移不起作用。我發現重新打包只是解決方案,但這可能不是最高性能的解決方案。簡單的演員是否有可能?C++將一個向量<specific_type>投射到向量<boost :: variant>
小例子:
#include "boost/variant.hpp"
#include <string>
#include <vector>
typedef boost::variant<int, std::string> test_t;
void inner(std::vector<test_t> a) {}
void outer(std::vector<int> a) {
// the following does not work:
//inner(a);
//inner((std::vector<test_t>) a);
//inner(const_cast<std::vector<test_t>>(a));
//inner(reinterpret_cast<std::vector<test_t>>(a));
//inner(static_cast<std::vector<test_t>>(a));
//inner(dynamic_cast<std::vector<test_t>>(a));
// only "valid" solution
std::vector<test_t> b;
for (const int i : a) {
b.push_back(i);
}
inner(b);
}
int main()
{
std::vector<int> a = { 1, 4, 2 };
outer(a);
}
這樣可以避免額外的內存分配,但是也會迭代完整的向量?當然,這個語法相當不錯。 – gerion
@gerion沒有辦法繞過。你必須爲每個元素構建一個「變體」 - 如果沒有真正查看所有元素,就無法做到這一點。 – Barry
@gerion,你至少可以將對象移動到變體矢量嗎? –