static_cast's argument forwarding - c++

Suppose i don't like the name of static_cast operator and want to wrap it in a function with a different name, say fancy_static_cast but perfectly preserving the semantics. How should i do it? More specifically does static_cast accept it's argument by value or by reference? Or does it depend on the argument expression? Should i provide several overloads or will something like this do the trick?
template <typename To, typename From>
To fancy_static_cast(From&& from)
{
return static_cast<To>(std::forward<From>(from));
}

Suppose i don't like the name of static_cast operator and want to wrap it in a function with a different name, say fancy_static_cast but perfectly preserving the semantics. How should i do it?
You shouldn't.
Instead, you say static_cast when you mean static_cast. Otherwise you will achieve only a lack of maintainability: Readers of your code will at first not recognize the static_cast, and when they look at the function they won't have an idea why the heck you did this and waste brainpower just to realize that you do essentially nothing.
Be clear and crisp with your code. Say what you mean, don't delude the readers (including yourself) by being overly fancy. Don't use misleading namings, instead try to use the parts of the language everybody knows by heart. Give yourself and others as few as possible opportunities to misunderstand what you have written.

Related

Why is the `std::sto`... series not a template?

I wonder if there is a reason why the std::sto series (e.g. std::stoi, std::stol) is not a function template, like that:
template<typename T>
T sto(std::string const & str, std::size_t *pos = 0, int base = 10);
and then:
template<>
int sto<int>(std::string const & str, std::size_t *pos, int base)
{
// do the stuff.
}
template<>
long sto<long>(std::string const & str, std::size_t *pos, int base)
{
// do the stuff.
}
/* etc. */
In my sense, that would be a better design, because for the moment, when I have to convert a string in whatever numerical value an user want, I have to manually manage each case.
Is there a reason to not have such a template function? Is there an assumed choice, or is this just done like that?
Looking at the description of these functions at cppref, I note the following:
... Interprets a signed integer value in the string str.
1) calls std::strtol(str.c_str(), &ptr, base)...
and strol a "C" standard function that's also available in C++.
Reading further, we see: (for the c++ sto* functions):
Return value
The string converted to the specified signed integer type.
Exceptions
std::invalid_argument if no conversion could be performed
std::out_of_range if the converted value would fall out of the range of the result type or if the underlying function (std::strtol or
std::strtoll) sets errno to ERANGE.
So while I have no original source for this, and indeed have never worked with these functions, I would guess that:
TL;DR : These functions are C++-ish wrappers around already existing C/C++ functions -- strtol* -- so they resemble these functions as close as possible.
I have to manage manually each case. Is there a reason to not have such a template function?
In case of such questions, Eric Lippert (C#) usually says something along the lines:
If a feature is missing, then it's missing because noone implemented it yet. And that's because either noone else earlier wanted yet, or because it was considered not worth the effort, or because it couldn't have been finished before publishing the current release".
Here, I guess it's the "not worth" part, but I have neither asked the commitee about, nor managed to find any answer in old questions and faqs. I didn't spend much time searching though.
I say this because I suppose that most common of these functions' functionality (if not all of) is already contained in stream classes, like istringstream. Just like cin/etc, this one also has an all-having operator >>, overloaded for all base numeric types (and more).
Furthermore, the stream manipulators like std::hex (std::setbase) already solve the problem of passing various type-dependent configuration parameters to the actual conversion functions. No problems with mixed function signatures (like those mentioned by DavidHaim in his answer). Here's just a single operator>>.
So.. since if we have it in streams, if we already can read numbers/etc from strings with simple foo >> bar >> setbase(42) >> baz >> ..., then I think it was not worth the effort to add more complicated layers to old C runtime functions.
No proof for that though. Just a hunch.
The problem with template specialization is that the specialization requires you to match the original template function signature, so each specialization must implement the interface of (string,pos,base).
If you would like to have some other type which does not follows this interface, you are in trouble.
Suppose that, in the future, we would like to have sto<std::pair<int,int>>. We will want to have pos and base for the first and the second stringified integer. we would like the signature to be in the form of string,pos1,base1,pos2,base2. Since sto signature is already set, we cannot do it.
You can always wrap std::sto* in your implementation of sto for integral types, but you cannot do that the other way around.
The purpose of these functions is to provide simple conversions for common cases. They are not intended as a general-purpose conversion suite. std::ostringstream is much better for that kind of thing.
In my sense, there would be a better design, because for the moment,
when I have to convert a string in whatever numerical value an user
want, I have to manage manually each case.
No, it would not. Templates goal (deliberately setting T-MP apart) is not to replace overloading; you should always prefer overloading to templates. Actually, it's something the language already does for you! Between a candidate function and a possible template instantation, the former will be prefered. Using language features for the sake of it is bad.
I don't see how templates could help either. Whatever type the user decides to input, it won't be known till runtime, and template types are deduced at compile time. C++ is a statically typed language. In this case, templates will just add an unneeded layer of complexity over normal function overloading.

Why is std::pair<A,B> not the same as std::tuple<A,B>? (Is there really no way?)

Why is std::pair<A,B> not the same as std::tuple<A,B>? It always felt strange to not be able to just substitute one with the other. They are somewhat convertible, but there are limitations.
I know that std::pair<A,B> is required to have the two data members A first and B second, so it can't be just a type alias of std::tuple<A,B>. But my intuition says that we could specialize std::tuple<A,B>, that is a tuple with exactly two elements, to equal the definition of what the standard requires a std::pair to be. And then alias this to std::pair.
I guess this wouldn't be possible as it is too straight-forward to not to be already thought of, yet it wasn't done in g++'s libstdc++ for example (I didn't look at the source code of other libraries). What would the problem of this definition be? Is it "just" that it would break the standard library's binary compatibility?
You've gotta be careful about things like SFINAE and overloading. For example, the code below is currently well-formed but you would make it illegal:
void f(std::pair<int, int>);
void f(std::tuple<int, int>);
Currently, I can disambiguate between pair and tuple through overload resolution, SFINAE, template specialization, etc. These tools would all become incapable of telling them apart if you make them the same thing. This would break existing code.
There might have been an opportunity to introduce it as part of C++11, but there certainly isn't now.
This is purely historical. std::pair exist since C++98 whereas tuple came after and was initially not part of the standard.
Backward compatibility is the biggest burden for C++ evolution, preventing some nice things to be done easily !
I've not tried this and don't have the bandwidth right now to do so. You could try making a specialisation of std::tuple, derived from a sd::pair. Someone please tell me this won't work or is particularly horrible idea. I suspect you'd run into trouble with accessors.

Explicit function template specialization - Why?

I keep reading and researching, different posts, c++ books, articles and so far nobody has explained the rational for this construct to me. It makes no sense and its really bugging me. The whole point of a template is to parameterize types to functions (or classes, but i'm talking specifically function template, not class). Why use funny template syntax without the type parameter???
//this seems ridiculous. why would anybody ever use this?
template<> void Swap(int & a , int & b){}
//I would always use this if I needed to take care of a special case, no?
void Swap(int & a , int & b){}
What am I missing? I would really appreciate some insight, and I do understand that function template specialization is not all that useful in practice anyway, but i still want to understand why it was ever invented in the first place. Whoever came up with it must have had a reason which seemed compelling enough at the time.
Thanks.
Great question! Function template specialisation is a bit niche and not generally worth it. You might be a bit confused as to the reason though.
You ask "what's the funny template syntax without a type parameter?" Plenty of use! Specialising templates is very important and useful, and the good old swap example is a classic reason to consider it. A template embodies the idea of a generic algorithm that works with any type, but often if you know a bit about the type you can drop in a much better algorithm, without calling code needing to know that anything different is happening under the hood. Only the compiler knows and it pulls in the best implementation for the real types at the point where the algorithm is instantiated with specific types, so your fast swap happens without the sorting algorithm needing special cases. Specialisation is a key part of making generic programming useful in the real world (or we'd have to use un-generic versions to get the performance we need).
Function template specialisation though is a bit niche, for more obscure reasons. I guess you've read Herb Sutter's summary? So, if you don't want to be caught out, it's a good idea to avoid specialising function templates. (std::swap is an example though of something you have to specialise rather than overload if you want to be ultra-conformant to the standard. We do this widely in our codebase here and it works well in practice, though overloading would probably work well enough too.)
So, please, specialise away all you like. Having class template specialisations, far from being "ridiculous" is often vital, but function template specialisation isn't as useful.

Use boost::function as function argument?

I want to call a function foo and let it behave differently.
(I'm adopting Strategy or Command pattern. They look similar to me.)
My overall plan is as follows..
First, define foo to take boost::function type
foo(boost::function<someType> execFunction)
{
// do something
execFunction(args);
// do something
}
Then, I give foo() different functions(as argument) depending on what I want.
Would this work? or Would you advise against it?
Any comments are welcome.
edit
Minor related question is,
sometimes execFunction needs 1 argument, and other times it needs 2 arguments.
I could use boost::function for both cases and just ignore the 2nd argument when not needed.
Is there a cleaner way to do this?
This works very well. But sometimes it is preferable to work with a
functor so your callers are free to choose what is best for them and to prevent the smalll overhead that comes with a boost::function:
template<typename Func>
void foo(Func f) {
f(myArgs);
}
You can also add an overload for the specific boost::function to take the object by reference.
template<>
void foo(const boost::function<void (expectedtypes)>& f) {
f(myArgs);
}
And possibly have that overloaded for constness as well.
For the case of accepting boost::function objects of different arity, I'd use overloading. If you go that route, avoid the templated version as you are going to run into trouble as soon as your users try to work with functors (as opposed to boost::function with different arity). This trouble is resolvable, but can get messy. You would need to dispatch the call to something that detects the arity of the funtor and executes the proper call. But as you said that templates are your weak-point, this isn't really recommended.
That is a common pattern, and will work. I have used that in the past and will most probably use it in the future. I try to use it only in some specific use cases, as it reduces drastically coupling, and while that is good in general, it makes it harder to follow the flow of control from the code (i.e. if you abuse it, it will be really hard to find what your program is meant to do other than running it in the debugger). But for specific tasks it is fine.
If you do not need to store the function<> for later use, or any runtime polymorphic behavior on the callee side, you can also consider using a function template, so that callers don't need to convert to function<> before executing your function.

const for non-reference arguments

If I have this code:
void Foo(aBasicType aIn) //Where aBasicType is int, char etc.
{
//...
}
Is there any point in making it const aBasicType since it is going to be copied anyway? One of the reasons I am asking is because I have seen it in 3rd party code and was wondering if there is something I am not aware of.
It cannot hurt to declare it const if you know that your function needs not modify its value during execution.
Note that functions that change their arguments, when arguments are passed by value, should be rare.
Declaring your variable const can prevent you from writing if (aIn = someValue).
I sometimes (infrequently) do it, when there is temptation to modify aIn in-place instead of making another copy, yet the method relies on aIn remaining unchanged throughout. It tends to be a close call though.
The reason is informative: you want the compiler to warn/error when a value-passed argument is seen on the left of an assignment.
It's a bit cumbersome, seen on libs whose audience may be less than "well informed" on C or C++ (it's the same for both languages).
That would make the value const for that function, which might be useful in the same way declaring a constant at the top of your function might be useful.
No, adding const to a scalar call-by-value parameter is meaningless and will only be confusing.
I prefer to add const qualifier to input paramters regardless to parameter passing method (by value, by pointer or by reference). So const parameter simply means "input parameter" and non-const parameter means "output parameter" (or, rarely, inout parameter). I suppose such a convention makes code more understandable but it is matter of taste, of course.
I think I can formulate this much simpler. When footype is not a template parameter:
const footype & in the signature is a guarantee for the caller of
the function and a constraint for the implementer of the function.
const footype on the other hand is only a constraint for the
implementer and irrelevant to the caller.
When footype is a template parameter, then the rules can only be tested against the individual template instantiations.
BTW, if you see const constraints, then the connected code is much easier to read because the possibilities of what the code can do is much restricted. This is one of the many reasons why C++ is easier to read than C# or Java.