为什么模板参数推导不起作用?

Why isn't template argument deduction working?

本文关键字:不起作用 参数 为什么      更新时间:2023-10-16

下面的玩具程序将一种类型的音乐转换为相应的颜色。它编译和执行得很好——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;
}

boost::assign::map_list_of可能不是map<K,V>类型,而是可以转换为它的某种类型。

编译器正试图从前2个参数和最后1个参数中推导出类型。最后一个1没有意义,所以它放弃了。

我们可以阻止对最后一个参数的推导,如下所示:

template<class T>struct tag{using type=T;};
template<class Tag>using type_t=typename Tag::type;
template<class T>using block_deduction=type_t<tag<T>>;
template<typename Key, typename T>
T convert(const Key &k, const T &d, const block_deduction<std::map<Key, T>> &m) {
  typename std::map<Key, T>::const_iterator it = m.find(k);
  return it == m.end() ? d : it->second;
}

鲍勃应该是你的叔叔。

在C++03:中

template<class T>struct no_deduction{typedef T type;};
template<typename Key, typename T>
T convert(const Key &k, const T &d, const typename no_deduction<std::map<Key, T>>::type &m) {
  typename std::map<Key, T>::const_iterator it = m.find(k);
  return it == m.end() ? d : it->second;
}

这在逻辑上是等价的,但更丑陋。

正如Yakk在回答中提到的,boost::assign::map_list_of不是std::map,但它可以转换为1。如果你不想改变你的功能,你可以改变你创建地图的方式。有了C++,我们现在有了可用于构造对象的初始值设定项列表。使用初始值设定项列表,我们可以更改
COLOR c = convert<MUSIC, COLOR>(COUNTRY, WHITE,
    boost::assign::map_list_of (RAP, RED) (EDM, BLUE) (ROCK, RED));

COLOR c = convert(COUNTRY, WHITE, {{RAP, RED},{EDM, BLUE},{ROCK, RED}});

这将使用相同的结果,并允许模板类型的推导工作。

实例