代码之家  ›  专栏  ›  技术社区  ›  Benjamin Lindley

为什么不能在此模板函数中推导类型?

  •  4
  • Benjamin Lindley  · 技术社区  · 15 年前
    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'
    

    1 回复  |  直到 14 年前
        1
  •  15
  •   Johannes Schaub - litb    15 年前
    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 称为非推导上下文,不能用于推导 .