-1

I have this functor class :

#include <string> using namespace std; class IsPlayerOfType { public: IsPlayerOfType(const string& type) : type_(type) {} bool operator()(const Player* player) const { return (player->getType() == type_); } private: string type_; }; 

The class "Player" represent a player that has several methods and attributes. Among them, there is the method getType() which returns a string.

At some point of my program I have a variable called players_ which is of type vector<Player*>

Finally I have the following code to count the number of players of a certain type in my vector :

int number = count_if(players_.begin(), players_.end(), IsPlayerOfType("Defensive")); 

When compiling I get a lot of errors such as :

  • error C2011: 'IsPlayerOfType' : 'class' type redefinition
  • error C2440: '' : cannot convert from 'const char [10]' to 'IsPlayerOfType'
  • error C2780: 'iterator_traits<_Iter>::difference_type std::count_if(_InIt,_InIt,_Pr)' : expects 3 arguments - 2 provided

    I don't understand very well how count_if works, I tried to write this code inspiring myself from this answer : https://stackoverflow.com/a/13525420

    I don't see where I'm wrong and the compiler errors confuse me.

4
  • On which lines do you receive these errors? Commented Nov 6, 2014 at 21:47
  • Does this really need to be a functor? Commented Nov 6, 2014 at 21:48
  • What happens if you create the functor before the count_if call, i.e., IsPlayerOfType checker("Defensive"); and pass that to count_if? Commented Nov 6, 2014 at 21:51
  • Yes I have to use a functor in that case (application design requirements) Commented Nov 6, 2014 at 21:54

1 Answer 1

5

My psychic debugging skills tell me that you forgot the #define include guards in the header that defines IsPlayerOfType causing the header to be multiply included in some source file. Keep in mind that #include works by the preprocessor doing text substitution which means the preprocessor would need additional logic to even attempt to prevent multiple inclusion.

Also note that using at file scope in a header is quite dangerous and should be avoided.

Sign up to request clarification or add additional context in comments.

2 Comments

You were right (#ifndef thing), I just don't understand why in c++ we should write this everywhere because it NEEDS to be written everywhere. It just like telling the program all the things it should not do (which is an infinite list of things) I don't understand why it's not automatic. Is there a situation where multiple inclusions are useful ?
@singe31 I've only encountered that situation once, but when I did it was super useful. The gist of it was I used macros and inclusion to auto-generate code and help prevent typos.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.