我想让一些模板函数与现有的模板结构助手一起使用。但是模板参数推断失败。有解决办法吗?
这个重载的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<<(
^
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
};
答案 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;
}