我一直在尝试做这些简单的事情,而Visual Studio 2008似乎并不喜欢它。
template <class CharType>
class SomeClass
{
public:
template <class T1, class T2>
static bool SomeOperator(const typename T1::const_iterator& p_Begin1,
const typename T1::const_iterator& p_End1,
const typename T2::const_iterator& p_Begin2,
const typename T2::const_iterator& p_End2)
{
// do some stuff..
}
};
用这样的话来称呼它:
std::wstring a;
OtherString b;
SomeClass<wchar_t>::SomeOperator(a.begin(), a.end(), b.begin(), b.end());
我得到的是编译器错误,表明它无法推断出模板参数T1和T2
error C2783: 'bool SomeClass<CharType>::SomeOperator(const T1::const_iterator &,const T1::const_iterator &,const T2::const_iterator &,const T2::const_iterator &)' : could not deduce template argument for 'T1'
error C2783: 'bool SomeClass<CharType>::SomeOperator(const T1::const_iterator &,const T1::const_iterator &,const T2::const_iterator &,const T2::const_iterator &)' : could not deduce template argument for 'T2'
答案 0 :(得分:3)
编译器根本无法从此上下文中推断出类型。
假设std::wstring::const_iterator
实际上是const wchar_t*
,这很可能。在这种情况下,编译器如何知道它应该替换std::wstring
而不是任何其他类型T
T::const_iterator
为const wchar_t*
(也许vector<wchar_t>
)?
编译器无法确切地说出来。出于类似原因,您无法在函数调用中推断出some_template<T>::type
。
在您的情况下,解决方法很简单。您实际上并不需要容器类型 - 迭代器类型上的模板将正常工作:
template <typename I1, typename I2>
static bool SomeOperator(const I1& p_Begin1, const I1& p_End1,
const I2& p_Begin2, const I2& p_End2)
{ /* stuff */ }
如果您发现自己处于需要容器类型的情况,则必须传递容器或在函数调用中明确指定类型。
答案 1 :(得分:1)
编译器无法推断迭代器参数实际上是提供它们的容器的内部类型defs。
使用directyl两个迭代器类型:
template< typename IT1, typename IT2>
static bool SomeOperator(const IT1& p_Begin1,
const IT1& p_End1,
const IT2& p_Begin2,
const IT2& p_End2)
{
// do some stuff..
}
答案 2 :(得分:0)
您可能需要明确SomeOperator
的类型:
SomeClass<wchar_t>::SomeOperator<std::wstring, std::wstring>(a.begin(), a.end(), b.begin(), b.end());
我知道这看起来很烦人,但实际上编译器从嵌套定义(如T::const_iterator
)中推导出容器类型实际上相当困难(有时也是不可能)。从const_iterator
回到T
并不是直截了当的AFAIK。