我在VS2012 Nov 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;
}
答案 0 :(得分:2)
您在专业化中缺少<>
:
template<> class Test<std::map>
{
...
};
template<> class Test<std::unordered_map>
{
...
};
<强>更新强>
使用三个令牌序列引入完全专业化:
template
,<
和>
。声明也需要相同的前缀 全功能模板专业化。早期的C ++设计 语言不包含此前缀,但添加了成员 模板需要额外的语法来消除复杂的歧义 专业化。 [C ++模板,Vandervoorde等。第190页]。
答案 1 :(得分:1)
一种方法是:
#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 << "General\n"; }
};
template<typename ... T>
class Test<std::map, T...>
{
public:
typedef std::map<T...> container_type;
static void print() { std::cout << "Map\n"; }
};
template<typename ... T>
class Test<std::unordered_map, T...>
{
public:
typedef std::unordered_map<T...> container_type;
static void print() { std::cout << "Unordered Map\n"; }
};
int main() {
Test<std::vector, int>::print();
Test<std::map, int, int>::print();
Test<std::unordered_map, int, int>::print();
}