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?
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.
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.
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.
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)...);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With