Peter
Peter

Reputation: 425

Pass functor to constructor

I have a class that basically needs to store a functor given in the constructor, similar to this:

template <class T>
class Foo {
   private:
     T func;
   public:
     Foo(T f) : func(f) { }
}

However, to create a new instance of the Foo class, the I can't seem to do this:

Foo foo(std::less<int>());

because T is a class template parameter. I have to use this clunky syntax instead:

Foo<std::less<int>> foo(std::less<int>());

Is there a better way to do this, without writing the type of the functor twice?

Upvotes: 0

Views: 1246

Answers (2)

juanchopanza
juanchopanza

Reputation: 227418

Foo is not a class, it is a class template. You have to instantiate it with a template argument in order to create a type.

Concerning your example, you could add a default constructor for functors that are default constructible, like std::less et al.

template <class T>
class Foo {
   private:
     T func;
   public:
     Foo() = default; // C++03 would require Foo() {}
     Foo(T f) : func(f) { }
};

then

Foo<std::less<int>> foo;

Alternatively, you can provide a function template that takes a functor and returns a Foo<F> object.

Upvotes: 4

Casey
Casey

Reputation: 42554

You could use a function to deduce the functor type and return the correct Foo flavor:

template <typename T>
Foo<T> make_foo(T t) { return Foo<T>(t); }

but this solution basically needs auto from C++11 to store the return value:

auto f = make_foo(std::less<int>());

Upvotes: 2

Related Questions