-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.

Community
  • 1
  • 1
singe3
  • 2,065
  • 4
  • 30
  • 48

1 Answers1

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.

Mark B
  • 95,107
  • 10
  • 109
  • 188
  • 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 ? – singe3 Nov 06 '14 at 23:15
  • 1
    @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. – Mark B Nov 07 '14 at 01:25