[英]Can't deduce template parameter when helper template struct is used
我想使某些模板函数与现有的模板结构帮助器一起使用。 但是,模板参数推导失败。 有解决方法吗?
这个重载的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'
铛错误:
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
};
这是一个非推论上下文 ,不限于C ++ 03。 请参阅我以前的答案无法推导Template参数 。
作为一种解决方法,您需要在函数中可以推论出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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.