Perché non è possibile il tipo di dedurre in questa funzione template?
Domanda
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'
Funziona se a specificare letto
Soluzione
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));
}
o
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));
}
Il motivo per il vostro non è il lavoro, perché non è sufficiente per determinare T se si conosce il tipo dell'argomento. Che cosa succede se enable_if
sarebbe un modello come la seguente?
template<int N, typename T> struct A { typedef int type; };
Ogni T
in <std::is_pod<T>::value, T>
avrebbe fatto. In generale, un tipo di parametro funzione formata da ...T...::type
è chiamato un contesto non dedotta e non può essere utilizzata per dedurre T
.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow