C++ - 使用initializer_list作为参数的模板函数

标签 c++ c++11 templates initializer-list

我编写了一个简单的函数来计算 std::initializer_list 的最小值,如下所示:

template<typename T>
inline T min(const std::initializer_list<T>& values) {
    T minValue = values[0];
    for ( const auto& v : values )
        if ( v < minValue ) minValue = v;

    return minValue;
}

但我收到以下错误:

error C2027: use of undefined type 'T'
error C2226: syntax error: unexpected type 'std::initializer<_Elem>'
error C2988: unrecognizable template declaration/definition
error C2059: syntax error: ')'
error C2143: syntax error: missing ';' before 'identifier'

我尝试使用 std::vector 更改 std::initializer_list 并且没有错误。这是否意味着我们不能使用 std::initializer_list 作为参数来定义模板函数?我使用的是 Visual Studio 2013。

最佳答案

查看documentationstd::initializer_list 没有 operator[],所以这一行:

T minValue = values[0];

无效。您可以将其替换为:

T minValue = *values.begin();

关于C++ - 使用initializer_list作为参数的模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40089839/

相关文章:

c++ - 减少通过 UDP 套接字发送的数据

c++ - 从 C++ 文件中读取包含 std::vector 的对象

c++ - 模板类继承

c++ - 在运行时在 C++ 中组合几个类的类

c++ - cvSetImageROI 似乎不够快

c++ - 更改Qt库的路径

c++ - 每次循环迭代都使用相同的随机数

带 bo​​ost 的 C++11 占位符

c++ - 基类模板成员函数隐藏在派生类中,尽管参数列表不同

c++ - 将 C 程序的值发布到网页