Search code examples
c++templatespredicatefunctorc++98

How do i pass a predicate function as a template parameter?


I have a simple predicate:

class less_than
{
  int  x;

public:
  less_than(int i):
    x(i)
  {
  }

  bool  operator()(int i) const
  {
    return i < x;
  }
};

I have a container which looks like this:

my_containers<std::list<int>, less_than, int> myCont(list_1, list_2, less_than(11));
  • The first parameter says what's the type of the list_1 and list_2.
  • The second parameter says the name of the predicate.
  • The third parameter says what's the item type of the list_1 and list_2.

I tried to create my template like this:

template<class Type, class Predicate, class Item_Stored>
class my_containers
{
public:
  my_containers(Type &tar_1, Type &tar_2, Predicate felt)
  {
    ItemList_1 = tar_1;
    ItemList_2 = tar_2;
    predIcate  = felt;
  }

  my_containers & insert(const Item_Stored put_in)
  {
    if (!predIcate.operator()(put_in))
    {
      ItemList_1.insert(ItemList_1.end(), put_in);
    }
    else
    {
      ItemList_2.insert(ItemList_2.end(), put_in);
    }

    return *this;
  }

private:
  Type       ItemList_1;
  Type       ItemList_2;
  Predicate  predIcate;
};

Every time i use .insert(x), it should add the x to the first list if it is less than the given less_than::x otherwise into the other list but it gives me this error:

Error   C2512   'less_than': no appropriate default constructor available   

How can i fix it?


Solution

  • your constructor demands the default constructor of each member. use member initializer list instead.

        my_containers(Type& tar_1, Type& tar_2, Predicate felt)
            :ItemList_1(tar_1), ItemList_2(tar_2), predIcate(felt){}
    

    refer to: https://en.cppreference.com/w/cpp/language/constructor.