C++,将向量<specific_type>转换为向量<提升::变体>

C++, cast a vector<specific_type> to vector<boost::variant>

本文关键字:gt lt 向量 转换 提升 变体 specific C++ type      更新时间:2023-10-16

我具有一个函数签名,该函数将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);
}

是一个简单的演员吗?

nope。没有这样的演员。

这可能不是性能最多的解决方案

正确,我们可以使用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()});
}