使用帮助程序模板结构时无法推导模板参数

时间:2018-02-02 09:38:16

标签: c++ c++03 template-deduction

我想让一些模板函数与现有的模板结构助手一起使用。但是模板参数推断失败。有解决办法吗?

实施例

这个重载的operator <<编译并运行:

template <typename T>
inline typename std::vector<T>&
operator<<(
    typename std::vector<T>& vec,
    const typename std::vector<T>::value_type& val)
{
    vec.push_back(val);
    return vec;
}

但是当我尝试使用帮助器struct时,这不会编译:

template<typename T>
struct Vector
{
    typedef std::vector<T> Type;
};

template <typename T>
inline typename Vector<T>::Type&
operator<<(
    typename Vector<T>::Type& vec,
    const typename Vector<T>::Type::value_type& val)
{
    vec.push_back(val);
    return vec;
}

gcc错误:

error: no match for 'operator<<' (operand types are 'std::vector<int>' and 'int')
    ...
note: candidate: 
'template<class T> typename Vector<T>::Type& operator<<
(typename Vector<T>::Type&, const typename Vector<T>::Type::value_type&)'
 operator<<(
 ^~~~~~~~
note:   template argument deduction/substitution failed:
note:   couldn't deduce template parameter 'T'

clang错误:

error: invalid operands to binary expression ('std::vector<int>' and 'int')
   vec << int(2);
   ~~~ ^  ~~~~~~
note: candidate template ignored: couldn't infer template argument 'T'
operator<<(
^

Live example

问题

  • 在这种情况下,什么阻止成功模板参数扣除?
  • 此案例是否有c++03解决方法?别名模板可以解决c++11
  • 中的问题

注意:在我的实际问题中,第二个参数不一定是T,我不能用它来推导出矢量类型。

注意2:真正的帮助器结构包含一些特定于平台的预处理,如下所示:

template <class T>
struct Helper
{
#if defined(_WIN32_WCE)
    typedef std::vector<T, WMHeapAllocator<T> > Vector;  
#else
    typedef std::vector<T> Vector;      
#endif
};

1 个答案:

答案 0 :(得分:2)

这是非推断的上下文,不限于C ++ 03。请参阅我之前的回答Template parameter cannot be deduced

对于变通方法,您需要在函数中创建一个可以推导出T的参数。一旦从一个地方推断出,编译器就会在其他地方使用它。

在您的情况下,如果您确定value_type将是T,那么使用此功能将起作用:

template <typename T>
inline typename Vector<T>::Type&
operator<<(
    typename Vector<T>::Type& vec,
    const T& val)
{
    vec.push_back(val);
    return vec;
}

此处T是从第二个参数推导出来的,并在第一个参数中使用。

编辑(反映问题编辑)

您不需要帮助类,模板模板解决方案可能更好:

template<template<typename, typename> class Container, class T, class U>
inline Container<T, U>&
operator<<(
        Container<T, U>& vec,
        const typename Container<T, U>::value_type& val)
{
    vec.push_back(val);
    return vec;
}
相关问题