Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alias for all overloaded methods?

I have a class Filter which has the method process overloaded for various inputs.

template< typename T >
class Filter
{ 
public:
    void process(T arr[], size_t len);
    T process(T one_value);
    void process(std::array &arr);
    void process(std::vector &v);
    //... many other variants

    using operator() = process;  // How to write proper?
}

I want to simplify the user code omitting process: filter.process(values) will become filter(values). I don't think that writing an overloaded operator() for every variant is good idea. There must exist a more convenient solution?

like image 448
kyb Avatar asked May 02 '16 19:05

kyb


People also ask

What is type alias in c++?

Type alias is a name that refers to a previously defined type (similar to typedef). Alias template is a name that refers to a family of types.

What is an overloaded function C++?

C++ lets you specify more than one function of the same name in the same scope. These functions are called overloaded functions, or overloads. Overloaded functions enable you to supply different semantics for a function, depending on the types and number of its arguments.

What do you mean by overloading of a function?

An overloaded function is really just a set of different functions that happen to have the same name. The determination of which function to use for a particular call is resolved at compile time. In Java, function overloading is also known as compile-time polymorphism and static polymorphism.


1 Answers

Since you already have templates in the mix; why not try a variadic template as well;

template <typename... Args>
auto operator()(Args&&... args)
// assuming non-reference returns
{
  return process(std::forward<Args>(args)...);
}

Alternatively; if references are returned form some of the overloads (not shown in the OP);

template <typename... Args>
decltype(auto) operator()(Args&&... args)
// caters for reference returns
{
  return process(std::forward<Args>(args)...);
}

For further completeness and broader use cases; if desired, the following offers SFINAE-friendly behaviour and depending on the compiler, shorter/easier error messages;

template <typename... Args>
auto operator()(Args&&... args) -> decltype(process(std::forward<Args>(args)...))
// SFINAE support using a trailing decltype
{
  return process(std::forward<Args>(args)...);
}
like image 141
Niall Avatar answered Nov 06 '22 17:11

Niall