I know the answer to the frequently-asked How do I specify a pointer to an overloaded function?: Either with assignment or with a cast, and every other C++ tutorial uppercases a string like this (give or take static_cast
):
transform(in.begin(), in.end(), back_inserter(out), (int(*)(int)) std::toupper);
Or like this:
int (*fp)(int) = std::toupper;
transform(in.begin(), in.end(), back_inserter(out), fp);
Which neatly selects the <cctype>
overload of std::toupper
.
But this begs the question: How can I select the <locale>
overload in a similar manner?
char (*fp2)(char, const std::locale&) = std::toupper;
transform(in.begin(), in.end(), back_inserter(out), fp2);
// error: too few arguments to function
Or, more practically, consider someone trying to use the C++11 std::stoi
in an algorithm to convert a vector of strings to a vector of integers: stoi
has two overloads (string
/wstring
), each taking two additional default arguments.
Assuming I don't want to explicitly bind all those defaults, I believe it is impossible to do this without wrapping such call in an auxiliary function or lambda. Is there a boost wrapper or TMP magic to do it for me in completely generic manner? Can a wrapper like call_as<char(char)>(fp2)
or, more likely, call_as<int(const std::string&)>(std::stoi)
even be written?
As a guideline, you shouldn't use a default argument as a flag upon which to conditionally execute code. You should instead break the function into two or more overloaded functions if you can. A default argument should be a value you would ordinarily put in that position.
Which of the following in Object Oriented Programming is supported by Function overloading and default arguments features of C++. Explanation: Both of the features allow one function name to work for different parameter.
In C++ programming, we can provide default values for function parameters. If a function with default arguments is called without passing arguments, then the default parameters are used. However, if arguments are passed while calling the function, the default arguments are ignored.
Two functions having same number of argument, order and type of argument can be overloaded if both functions do not have any default argument. Overloaded function must have default arguments.
It's funny, I was doing something similar. The best way I found to do it was using lambdas as follows, because otherwise, you have to use a typedef to get the right overload and a std::bind to get rid of the locale, or not use the locale. However, this works much more cleanly:
static const std::locale loc;
transform(in.begin(), in.end(), back_inserter(out), [&loc](char c) {
return std::toupper(c, loc);
});
I use the static to save the effort of reallocating each time.
Or you could get a typedef and do:
std::bind((LocaleCompare)std::toupper, std::placeholders::_1, loc); // UGLY!
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