本文介绍了将std :: vector作为模板模板参数传递错误 - 在GCC中工作,在MSVC中失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <deque>
#include <functional>

#define BEGIN_TO_END(container) container.begin(), container.end()

template <template<typename...> class OutputContainerType, class InContainer>
OutputContainerType<typename InContainer::value_type> convertContainer(const InContainer& in)
{
    OutputContainerType<typename InContainer::value_type> result;
    std::transform(BEGIN_TO_END(in), std::back_inserter(result), [](typename InContainer::value_type value) {return value;});
    return result;
}

int main() {
    std::deque<int> d {1, 2, 3};
    const auto v = convertContainer<std::vector>(d);
    std::cout << v.size() << std::endl;
}

适用于GCC()。但是,它不与MSVC 2013(12.0)一起编译时出现错误:'std :: vector':类没有构造函数(可以测试,选择12.0编译器版本)。

works fine with GCC (link). However, it doesn't compile with MSVC 2013 (12.0) with the error: 'std::vector' : class has no constructors (can be tested here, select 12.0 compiler version). What's the problem here, and how can I fix it?

推荐答案

代码:

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <deque>
#include <functional>

#define BEGIN_TO_END(container) container.begin(), container.end()

template <template<typename T, typename T2> class OutputContainerType, class InContainer>
OutputContainerType<typename InContainer::value_type, std::allocator<typename InContainer::value_type>> convertContainer(const InContainer& in)
{
    OutputContainerType<typename InContainer::value_type, std::allocator<typename InContainer::value_type>> result;
    std::transform(BEGIN_TO_END(in), std::back_inserter(result), [](typename InContainer::value_type value) {return value;});
    return result;
}

int main() {
    std::deque<int> d {1, 2, 3};
    const auto v = convertContainer<std::vector>(d);
    std::cout << v.size() << std::endl;
}

工作。这里的问题是可变数量的模板参数...

Worked. The problem is then with variadic number of template parameters here...

EDITED:
实际上没有模板的可变数参数,我甚至可以用

EDITED:Actually not with the variadic number of template parameters as I can even compile it with the

template <template<typename...> class OutputContainerType, class InContainer>

,因此MSVC编译器需要明确给出每种类型的模板。

so the MSVC compiler needs explicitly given each type of the template.

这篇关于将std :: vector作为模板模板参数传递错误 - 在GCC中工作,在MSVC中失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 22:13