Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 overloaded methods with forwarding to a unique method

Tags:

c++

c++11

I have the following class in c++11:

#include <iostream>
#include <string>
#include <utility>

void overloaded_function(const std::string& param) {
  someStuffHere
}
void overloaded_function(std::string&& param) {
  someStuffHere
}

As you can see the overloaded_function implementation is exactly the same. I would like to create a new function instead of having the same implementation into two different methods. I tried with:

void overloaded_function(const std::string& param) {
  uniqueCall(std::forward<std::string&>(param));
}
void overloaded_function(std::string&& param) {
  uniqueCall(std::forward<std::string&&>(param));
}
void uniqueCall(T&& param) {
    someStuffHere
}

but it doesn't work due to the lvalue reference not accepted by uniqueCall.

like image 448
greywolf82 Avatar asked Apr 09 '18 07:04

greywolf82


People also ask

What is method overloading in C #?

What is Method Overloading in C#? Method Overloading is the compile-time implementation of the concept of Polymorphism. Developers can define similar methods by the same name, differing in either the number of arguments, order of arguments, or type of arguments.

What is polymorphism and method overloading in C #?

In this article you will learn Method Overloading and Method Overriding in C#. Polymorphism means “Many Forms”. In Polymorphism, poly means “Many” and morph means “Forms.” Polymorphism is one of the main pillars in Object Oriented Programming.

How do I implement function overloading?

A user can implement function overloading by defining two or more functions in a class sharing the same name.

What is the role of return type in method overloading?

The return type of the methods does not play any role in method overloading. Optional Parameters take precedence over Implicit type conversion when deciding which method definition to bind. Implicit type conversion takes precedence over the parent class method. Exercise – To understand this, here is a little exercise for you.


1 Answers

If you don't need to modify the argument, you don't need an rvalue overload at all1. A const lvalue reference will happily bind to an rvalue.

That's how C++ always worked, and rvalue references don't change that.

So a simple

void overloaded_function(const std::string& param) {
  //someStuffHere
}

Will bind to an argument of whatever value category.


1 - And if you did need to modify it, then passing rvalues is a bit dubious.

like image 171
StoryTeller - Unslander Monica Avatar answered Oct 21 '22 06:10

StoryTeller - Unslander Monica