【问题标题】:Why can't the type be deduced in this template function?为什么这个模板函数不能推导出类型?
【发布时间】:2010-10-30 18:24:43
【问题描述】:
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'

如果我指定 read 就可以了。有没有办法让它从参数中推断出类型?

【问题讨论】:

    标签: c++ templates c++11 enable-if


    【解决方案1】:
    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; };
    

    &lt;std::is_pod&lt;T&gt;::value, T&gt; 中的任何 T 都会这样做。 一般而言,...T...::type形成的函数参数类型称为非推导上下文,不能用于推导T

    【讨论】:

    • 你说“一般”,有没有具体情况?
    • @GMan 我想不出另一种情况。固定。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-23
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    • 2018-12-09
    相关资源
    最近更新 更多