为什么不能在类型此模板功能可以推断?
题
template<typename T>
std::istream & read(std::istream & istr, typename std::enable_if<std::is_pod<T>::value, T>::type & value)
{
return istr.read( reinterpret_cast<char*>(&value), sizeof(T));
}
int main()
{
int x;
read(cin, x); // error here
}
error C2783: 'std::istream &read(std::istream &,std::enable_if<std::tr1::is_pod<_Ty>::value,T>::type &)' : could not deduce template argument for 'T'
它的工作原理,如果我指定阅读
解决方案
template<typename T>
std::istream & read(std::istream & istr, T value,
typename std::enable_if<std::is_pod<T>::value>::type* = 0)
{
return istr.read( reinterpret_cast<char*>(&value), sizeof(T));
}
或者
template<typename T>
typename std::enable_if<std::is_pod<T>::value, std::istream>::type &
read(std::istream & istr, T value)
{
return istr.read( reinterpret_cast<char*>(&value), sizeof(T));
}
你不工作的原因是因为它不足以决定T,如果你知道参数的类型。如果enable_if
会像下面的模板?
template<int N, typename T> struct A { typedef int type; };
在T
任何<std::is_pod<T>::value, T>
将做到这一点。 一般而言,通过...T...::type
形成的功能参数类型被称为非推测的上下文,并且不能被用于演绎T
。
不隶属于 StackOverflow