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++ - 使用 BMP - 加载和保存

c++ - 如何将 unique_ptr 参数传递给构造函数或函数?

c++ - 将 void* 与 uint16_t 进行比较

c++ - Qt Concurrent 或 std::async 用于新代码?

c++ - 如何使用 C++ 模板创建具有任意数量 case 的 switch 语句生成器?

c++ - 在 C++ 中从输入函数获取参数类型的模板函数出错?

c++ - 尝试在 C++ 中打印时超出 Unicode 范围

c++11 - 使用 operator new 作为仿函数/函数指针

c++ - CUDA 7.5 实验性 __host__ __device__ lambda

c++ - 由于无法解析模板参数导致多态性失败?