【发布时间】:2019-12-24 06:35:38
【问题描述】:
如何实现内部模板类型std::vector<std::vector<T>>的模板重载功能。
我有一个重载模板程序和一个包含映射、对和向量的复杂数据结构。
#include <iostream>
#include <vector>
#include <map>
#include <utility>
#include <typeinfo>
template<typename Test, template<typename...> class Ref> //#6
struct is_specialization : std::false_type {};
template<template<typename...> class Ref, typename... Args> //#7
struct is_specialization<Ref<Args...>, Ref>: std::true_type {};
template <typename T>
bool f(T& x) // #1
{
std::cout << "body of f\n";
return f(x);
}
template <typename T>
bool f(std::vector<T>& v) // #2
{
std::cout << "body of f for vectors\n";
return true;
}
template<typename T>
typename std::enable_if<is_specialization<typename T::value, std::vector>::value, T>::type
bool f(std::vector<T>& v) // #5
{
std::cout << "body of f for vectors<vectors>\n";
return true;
}
template <typename Key, typename Value>
bool f(const std::pair<Key,Value>& v) // #3
{
std::cout << "body of f for pairs\n";
for(auto& e: v) {
f(e.first);
}
for(auto& e: v) {
f(e.second);
}
return true;
}
template <typename Key, typename Value>
bool f(std::map<Key,Value>& v) // #4
{
std::cout << "body of f for maps\n";
for(auto& e: v) {
f(e.first); // expecting this call goes to #3
}
for(auto& e: v) {
f(e.second);
}
return true;
}
int main() {
std::vector<int> v{1,2};
std::map<std::pair<int,int>,std::vector<std::vector<int>>> m_map = {
{{10,20}, {{5,6},{5,6,7}}},
{{11,22}, {{7,8},{7,8,9}}}
};
f(m_map); // this call goes to #4
}
总是调用向量#2,但对于std::vectors<std::vector<T>>,我需要调用#5,并且我得到编译错误w.r.t ::type 在std::enable_if 中使用。
请让我知道这个程序有什么问题以及如何使它工作。
也有人能解释一下 #6 和 #7 表示 w.r.t 模板参数包是什么,它是如何工作的。
谢谢。
【问题讨论】:
-
你试过为
std::vector<std::vector<T>>写一个重载吗? (您的#6/#7 问题应该是一个单独的问题。) -
@Davis 是的,我没有成功,是的 #6 和 #7 我可以将其作为一个单独的问题
标签: c++ templates overloading stdvector template-specialization