【发布时间】:2019-12-19 08:39:26
【问题描述】:
模板重载在当前场景中不起作用。
我有一个重载模板程序和一个包含映射、对和向量的复杂数据结构。 没有为 std::pair 调用重载的模板函数。 我无法弄清楚它的原因。它正在调用#1 通用模板函数。
#include <iostream>
#include <vector>
#include <map>
#include <utility>
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 Key, typename Value>
bool f(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<int>> m_map = {
{{10,20}, {5,6}},
{{11,22}, {7,8}}
};
f(m_map); // this call goes to #4
}
控制台输出是
body of f for maps
body of f
body of f
body of f
body of f
body of f .... Goes on infinitely
请告诉我这段代码有什么问题。
谢谢。
【问题讨论】:
-
“无限继续”部分很容易解释:在调用
f(x)时的template <typename T> bool f(T& x)函数中,f唯一已知的重载就是它自己。这意味着你有一个无限递归。 -
顺便说一句,#3 的正文是错误的,您不能在对上进行迭代...
标签: c++ templates overloading template-specialization std-pair