如何将std::map传递到VS2013中的可变模板?

How can I pass a std::map to a variadic template in VS2013?

本文关键字:VS2013 std map      更新时间:2023-10-16

我有这个代码在VS2012十一月CTP工作:

//.h
template<template <typename...> class Container>
class Test {
    typedef Container<unsigned int, TestEntry> L1;
    Test();
    ...
}
//.cpp
template<template <typename...> class Container>    
Test<Container>::Test() {}
...
template class Test<std::map>;
template class Test<std::unordered_map>;
//main.cpp
#include "test.h"
#include <map>
#include <unordered_map>
int main()
{
    Test<std::map> test;
    std::cout << "COMPILES!!!" << std::endl;
    return 0;
}

我刚刚更新到Visual Studio 2013 Ultimate,它将无法编译,错误:

'std::map' : too few template arguments

我知道我可以放松模板的要求,如:

template< typename MapType>

但这对我来说不是一个很好的解决方案,因为我想自定义的唯一东西是容器类型,而不是内容。此外,内容很复杂,每次都要写,这是一个问题。

是否有办法解决这个在VS2013?我花了好几个小时想修好它,但还是没有成功。

更新:

在VS2013中精确复制:

//test.h
#include <map>
#include <unordered_map>
template<template <typename...> class Container>
class Test {
    typedef Container<unsigned int, unsigned int> L1;
};
//test.cpp
#include "test.h"
template<> class Test<std::map> {
public:
    typedef std::map<unsigned int, unsigned int> L1;
};
template<> class Test<std::unordered_map> {
public:
    typedef std::unordered_map<unsigned int, unsigned int> L1;
};
//main.cpp
#include "test.h"
#include <iostream>
#include <cmath>
#include <map>
#include <unordered_map>
int main()
{
    Test<std::map> test3;
    std::cout << "COMPILES!!!" << std::endl;
    return 0;
}

您在专门化中缺少<>:

template<> class Test<std::map>
{
...
};
template<> class Test<std::unordered_map>
{
...
};

更新:

一个完整的专门化由三个令牌组成:template, <>。声明时也需要相同的前缀全函数模板专门化。c++的早期设计语言没有包含这个前缀,而是添加了成员模板需要额外的语法来消除歧义专门化。[c++ Templates, Vandervoorde et al.].

一种方法是:

#include <iostream>
#include <map>
#include <vector>
#include <unordered_map>
template<template <typename...> class Container, typename ... T>
class Test
{
    public:
    typedef Container<T...> container_type;
    static void print() { std::cout << "Generaln"; }
};
template<typename ... T>
class Test<std::map, T...>
{
    public:
    typedef std::map<T...> container_type;
    static void print() { std::cout << "Mapn"; }
};
template<typename ... T>
class Test<std::unordered_map, T...>
{
    public:
    typedef std::unordered_map<T...> container_type;
    static void print() { std::cout << "Unordered Mapn"; }
};

int main() {
    Test<std::vector, int>::print();
    Test<std::map, int, int>::print();
    Test<std::unordered_map, int, int>::print();
}