[英]C++, cast a vector<specific_type> to vector<boost::variant>
我有一個函數簽名,它使用vector<specific_type>
作為參數,並調用另一個具有vector<boost::variant<specific_type, ...>>
作為參數的函數。 參數的簡單傳遞不起作用。 我發現重新包裝是唯一的解決方案,但這可能不是性能最高的解決方案。 一個簡單的演員有可能嗎?
最小示例:
#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);
}
一個簡單的演員有可能嗎?
不。 沒有這樣的演員表。
這可能不是最有效的解決方案
正確,我們可以使用vector
范圍構造函數做得更好:
template< class InputIt > vector( InputIt first, InputIt last, const Allocator& alloc = Allocator() );
我們將使用像:
void outer(std::vector<int> const& a) {
inner({a.begin(), a.end()});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.