C++,将 vector<specific_type> 转换为 vector<boost::variant>

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);
}

Is a simple cast somehow possible?

没有。没有这样的演员。

this is likely not the most performant solution

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