我编写了一个简单的函数来计算 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。
最佳答案
查看documentation , std::initializer_list
没有 operator[]
,所以这一行:
T minValue = values[0];
无效。您可以将其替换为:
T minValue = *values.begin();
关于C++ - 使用initializer_list作为参数的模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40089839/