【发布时间】:2015-10-06 09:17:26
【问题描述】:
以下玩具程序将一种音乐类型转换为相应的颜色。它编译和执行得很好——COUNTRY 的转换失败,正如预期的那样,conversion() 函数返回默认值,WHITE。但是,如果我删除模板参数<MUSIC, COLOR>,模板参数推导无法识别要使用的类型。我怎样才能让扣除工作?
#include <map>
#include <iostream>
#include "boost/assign.hpp"
template<typename Key, typename T>
T convert(const Key &k, const T &d, const std::map<Key, T> &m) {
typename std::map<Key, T>::const_iterator it = m.find(k);
return it == m.end() ? d : it->second;
}
enum MUSIC { ROCK, RAP, EDM, COUNTRY };
enum COLOR { RED, BLUE, ORANGE, WHITE };
int main()
{
COLOR c = convert<MUSIC, COLOR>(COUNTRY, WHITE,
boost::assign::map_list_of (RAP, RED) (EDM, BLUE) (ROCK, RED));
std::cout << c << std::endl;
}
【问题讨论】:
-
如果您也为地图类型添加模板参数会怎样?
-
template Map, typename Key, typename Value> ... 按照@jxh的建议?
标签: c++ templates boost assign template-argument-deduction