2017-02-17 69 views
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); 
} 

回答

3

是一個簡單的投某種程度上可能嗎?

沒有。沒有這樣的演員。

這很可能不是最高效的解決方案

正確的,我們能做到用好一點的vector range constructor

template< class InputIt > 
vector(InputIt first, InputIt last, 
     const Allocator& alloc = Allocator()); 

,我們會使用這樣的:

void outer(std::vector<int> const& a) { 
    inner({a.begin(), a.end()}); 
} 
+0

這樣可以避免額外的內存分配,但是也會迭代完整的向量?當然,這個語法相當不錯。 – gerion

+0

@gerion沒有辦法繞過。你必須爲每個元素構建一個「變體」 - 如果沒有真正查看所有元素,就無法做到這一點。 – Barry

+0

@gerion,你至少可以將對象移動到變體矢量嗎? –

相關問題