【发布时间】:2023-03-07 19:02:01
【问题描述】:
我想让一些模板函数与现有的模板结构助手一起工作。但是模板参数推导失败。有解决办法吗?
示例
这个重载的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
};
【问题讨论】:
-
在
C<T>::Type中,T是不可演绎的(我们可能有(在一般情况下)几个匹配的T)。 (在第一个带有::value_type的sn-p 中也是如此,所以T仅从第一个参数推导出来)。
标签: c++ c++03 template-argument-deduction