2

I wrote a simple function to calculate the min value of an std::initializer_list like this:

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; } 

But I get the following errors:

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'

I tried to change the std::initializer_list with an std::vector and there were no errors. Does this mean that we cannot define a template function using std::initializer_list as a parameter? I am using Visual Studio 2013.

15
  • 1
    Please provide a minimal reproducible example. Note that initializer_list doesn't have operator[]. Note also that std::min exists. Commented Oct 17, 2016 at 15:08
  • @Barry There is nothing else to provide this is the exact code that gives these errors. Without even calling min() function Commented Oct 17, 2016 at 15:09
  • 1
    really Commented Oct 17, 2016 at 15:10
  • What compiler are you using? Commented Oct 17, 2016 at 15:10
  • @Barry This min is inside a different namespace. And even if I remove everything inside the function and just return T(); I still get the same errors Commented Oct 17, 2016 at 15:10

1 Answer 1

3

Looking in the documentation, std::initializer_list has no operator[], so this line:

T minValue = values[0]; 

can not be valid. You can replace it with:

T minValue = *values.begin(); 
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your answer. I still get the same errors
I tested the code in rextester.com with visual compiler. It is working with a main function just executing std::cout << (min({1, 2, 3}));. You should edit your question with a complete example
Did you include <initializer_list>?
@wasthishelpful he said he did in the comments on the question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.