A constructor from a class I'm inheriting requires a non-trivial object to be passed in. Similar to this:
MyFoo::MyFoo() : SomeBase( complexstuff )
{
return;
}
The complexstuff has little to do with MyFoo, so I didn't want to have to pass it in.
Instead of writing some kind of 1-off temporary function that returns complexstuff I used a lambda. What took me a few minutes to figure out is I have to invoke the lambda. So my code now looks like this:
MyFoo::MyFoo() : SomeBase(
[]()
{
/* blah blah do stuff with complexstuff */
return complexstuff;
} () )
{
return;
}
If you didn't catch it, it is subtle. But after the lambda body, I had to put () to tell the compiler to immediately "run" the lambda. Which made sense after I figured out what I had done wrong. Otherwise, without the () to invoke the lambda, gcc says something similar to this:
error: no matching function for call to 'SomeBase(<lambda()>)'
But now that has me thinking -- did I do this correctly? Is there a better way in C++11 or C++14 to tell the compiler that I want it to immediately invoke a lambda I've written? Or is appending an empty () like I did the usual way to do this?
But now that has me thinking -- did I do this correctly?
Yes you did.
Is there a better way in C++11 or C++14 to tell the compiler that I want it to immediately invoke a lambda I've written?
Not that I know of. A lambda is also just a function object, so you need to have a () to call it, there is no way around it (except of course some function that invokes the lambda like std::invoke).
If you want you can drop the () after the capture list, because your lambda doesn't take any parameters.
Or is appending an empty () like I did the usual way to do this?
Yes, it is the shortest way. As said before, std::invoke would also work instead, but it requires more typing. I would say a direct call with () is the usual way it is done.
In C++17 you can use std::invoke. This does the exact same thing as you did, but perhaps you will find this clearer.
#include <iostream>
#include <functional>
void foo(int i)
{
std::cout << i << '\n';
}
int main()
{
foo( std::invoke( []() { return 1; } ) );
}
There's no way to tell the compiler to invoke the lambda immediately. The simplest course (both in terms of complexity and number of typed characters) is what you did already. It's also very idiomatic for anyone who has worked with languages that have closures (I'm thinking JavaScript here).
If you want to avoid the syntax, then either modify SomeBase or complexstuff to execute the callable.
If all you want is syntactic sugar for invoking the lambda, you can always do what something like Alexandrescu's SCOPE_GUARD does, and abuse operator overloading:
Live example
#include <iostream>
namespace detail {
enum class invoke_t{};
template<class Callable>
auto operator+(invoke_t, Callable c) -> decltype(c()) {
return c();
}
}
constexpr detail::invoke_t invoke{};
int main() {
invoke + []() {
std::cout << "called";
};
}
But I wouldn't. Inventing your own DSL will just make your code worse to maintain. Stick to the idioms that utilize plain language constructs.
Is there a better way
You could also consider having a private static member function building the complexstuff, something like
class MyFoo : public Base {
private:
static SomeComplexType compute_complex_stuff() {
SomeComplexType complexstuff;
/*compute the complexstuff */
return complexstuff;
};
public:
MyFoo() : Base(compute_complex_stuff()) {};
};
I don't know if it is better than defining a lambda expression and applying it immediately; that is IMHO a matter of taste; for a short lambda body I would prefer a lambda expression immediately applied (but perhaps some compiler would create the temporary closure in that case, so it might be slower without optimizations; I expect most C++11 compilers to be able to make that optimization).
BTW, GCC provides the statement expression language extension (also understood by Clang) for your purposes. With it you could write
MyFoo::MyFoo : Base (({
SomeComplexType complexstuff;
/*compute the complexstuff */
return complexstuff;
}) {};
Related
In this article, a technique is described to move error code out-of-line in gcc to help optimise the hot path for size as much as possible. An example of this would be:
#define unlikely(x) __builtin_expect (!!(x), 0)
bool testForTerriblyUnlikelyEdgeCase() {
//test for error condition here
}
void example() {
if (unlikely(testForTerriblyUnlikelyEdgeCase())) {
[&]() __attribute__((noinline,cold)) {
//error handling code here
}();
}
}
This is great technique, but requires an absolute ton of boilerplate. What's the best way to wrap this to reduce the boilerplate as much as possible? Ideally C++14 compatible allowing gcc-specific functionality.
Bonus Question: Is the unlikely(...) in the if statement redundant since the lambda is explicitly marked cold?
There are two approaches that come to mind:
A function-wrapper approach, and
A macro-based approach
Function Wrapper
The nicest in terms of design would be to wrap this functionality into a function that encapsulates the attributes and handling. To do this, you pass a callback that you want invoked as the cold handler (in this case, a lambda). It can look as simple as this (using C++11-attributes instead of __attribute__ syntax):
template <typename Fn>
[[gnu::cold]] [[gnu::noinline]]
void cold_path(Fn&& fn)
{
std::forward<Fn>(fn)();
}
You can also extend this solution to make use of the condition to test for, such as:
template <typename Expr, typename Fn>
void cold_path_if(Expr&& expr, Fn&& fn)
{
if (unlikely(std::forward<Expr>(expr))) {
cold_path(std::forward<Fn>(fn));
}
}
putting it all together, you have:
void example() {
cold_path_if(testForTerriblyUnlikelyEdgeCase(), [&]{
std::cerr << "Oh no, something went wrong" << std::endl;
std::abort();
});
}
Here's how it looks on Compiler Explorer.
Macro-based approach
If passing an explicit lambda is not desired, then the only alternative that comes to mind is a macro-based solution that creates a lambda for you. To do this, you will need a utility that will invoke the lambda immediately, so that all you need is to define the function's body:
// A type implicitly convertible to any function type, used to make the
// macro below not require '()' to invoke the lambda
namespace detail {
class invoker
{
public:
template <typename Fn>
/* IMPLICIT */ invoker(Fn&& fn){ fn(); }
};
}
This is done as a class that is implicitly convertible from the function, so that you can write code like detail::invoker foo = []{ ... }. Then we want to take the first part of the definition up to the capture, and wrap this into a macro.
To do this, we will want a unique name for the variable, otherwise we may shadow or redefine variables if more than one handler is in the same scope. To work around this, I append the __COUNTER__ macro to a name; but this is nonstandard:
#define COLD_HANDLER ::detail::invoker some_unique_name ## __COUNTER__ = [&]() __attribute__((noinline,cold))
This simply wraps the creation of the auto invoker up until the point that the lambda is defined, so all you need to do is write COLD_HANDLER { ... }
The use would now look like:
void example() {
if (unlikely(testForTerriblyUnlikelyEdgeCase())) {
COLD_HANDLER {
//error handling code here
};
}
}
Here's an example on compiler explorer
Both approaches produce identical assembly to just using the lambda directly, with only the labels and names being different. (Note: This comparison uses std::fprintf instead of stds::cerr so the assembly is smaller and easier to compare)
Bonus Question: Is the unlikely(...) in the if statement redundant since the lambda is explicitly marked cold?
Reading GCC's documentation for __attribute__((cold)) seems to indicate that all branches leading to the cold function are marked unlikely, which should make the use of the unlikely macro redundant and unnecessary -- though it shouldn't hurt to have it.
From the attributes page:
The cold attribute is used to inform the compiler that a function is unlikely executed. The function is optimized for size rather than speed and on many targets it is placed into special subsection of the text section so all cold functions appears close together improving code locality of non-cold parts of program. The paths leading to call of cold functions within code are marked as unlikely by the branch prediction mechanism. It is thus useful to mark functions used to handle unlikely conditions, such as perror, as cold to improve optimization of hot functions that do call marked functions in rare occasions.
Emphasis mine.
I'd like to reduce amount of syntax required to refer to a function and was wondering if there was a way to do something like:
(NOT COMPILABLE)
using pushToLastUsed = mSomeLongStackFIFOObject.push_back;
// or
auto pushToLastUsed = mSomeLongStackFIFOObject.push_back;
then I could to something like:
pushToLastUsed(10);
instead of:
mSomeLongStackFIFOObject.push_back(10);
Of course I could make a macro like:
#define pushToLastUsed mSomeLongStackFIFOObject.push_back
// some code using it here
#undef pushToLastUsed
but I'd prefer not to use macros.
One solution might be to use a lambda expression to capture the function call into a callable object :
#include <vector>
void foo(std::vector<int> & bar)
{
auto pushToLastUsed = [&bar](int index) {
bar.push_back(index);
};
pushToLastUsed(10);
}
Though in my opinion there is very little to gain from doing this, even if you replace bar with a very long identifier.
My first idea was something along the line of the other answer. On a second read of your question I understand that it is mainly the long name of the object that you want to avoid to repeat. Hiding a call to a standard function should be done with care as its main effect is to obfuscate your code. Everybody knows what push_back does, but even you will likely forget what exactly pushToLastUse does. A different option is to alias only the mSomeLongStackFIFOObject with a shorter name as in
auto& short_name = mSomeLongStackFIFIObject;
short_name.push_back(10);
When you're writing mSomeLongStackFIFOObject.push_back(10); you're actually calling SomeLongStackFIFOClass::push_back(&mSomeLongStackFIFOObject, 10);
One option is to do:
auto& m= mSomeLongStackFIFOObject;
And then:
m.push_back(10);
It will shorten it and still let you use any variable you like.
If the variable is global, you can always do:
static inline void pushBack(int n) { mSomeLongStackFIFOObject.push_back(n); }
If you're trying to shorten the access, I can guess that you're using the variable more than once; then it could make sense to try to put all the accesses in a function that belongs to the class.
You can achieve the desired behaviour by binding the object mSomeLongStackFIFOObject to the member function push_back and using a placeholder for its argument. This requires at least a C++11 compiler.
Consider the following example:
#include <functional>
#include <iostream>
struct A {
void push_back(const int& n) { std::cout << "push_back(" << n << ")\n"; }
};
int main() {
A mSomeLongStackFIFOObject;
std::function<void(const int&)> pushToLastUsed = std::bind(
&A::push_back,
&mSomeLongStackFIFOObject,
std::placeholders::_1
);
pushToLastUsed(10); // push_back(10)
}
Some notes about this:
As Mirko already mentioned correctly, calling a non-static member function is basically the same as calling a static member function with this as implicit first parameter. The binding of an instance of struct A as first parameter makes use of this fact.
Type inference using auto does work for member functions without any parameters but not in the case above.
If the non-static member function is overloaded (e.g. std::vector<T>::push_back) you have to explicitly state the template parameters for the function template std::bind. See Using std::tr1::bind with std::vector::push_back
or Are there boost::bind issues with VS2010? for further information.
in C/C++ (possibly pre-C++11), is it possible to do
A (*eval(A (*function)(B), B b))(){
// ... ??
}
i.e., a function taking
a function returning an A value from a B value,
a B value to be fed to that function,
which returns
- a function returning an A from ()
...??
If yes, would it be
efficient??
guaranteed the compiler generates code
which is not executed before call of the returned function??
Thanks in advance & cheers, Nick
2014-4-20 (1): Thanks for mentioning the 'evtl.'(fixed) std::bind. :-)
So – to understand – (in C/pre C++11 without Boost) function pointers are exceptional in the way that, inside functions, it is only possible to declare them, but there is no way to produce or modify an instance – as function/method definitions are the only possible sources for function pointer instances, from where these may be handed over either explicitly, or by function/method arguments??
Just asking, as I am not clear about a possible internal representation of function pointers...
2014-4-20 (2): With the contribution of Danvil, it's time for the purpose to reveal, here the same with templates:
template<typename T,typename A>
struct Evaluator {
T(*f)(A);
A a;
T operator()() const { return f(a); }
};
template<typename T,typename A>
Evaluator<T,A> eval(T(*f)(A), A a) {
Evaluator<T,A> w;
w.f= f; w.a= a;
return w;
}
This works, while – as some already might guess – the whole, from arbitrary matching function/arguments collections, is intended to be sent as a zero parameter procedure into a single function/method handling execution similar to a try/catch.
For not having to use mostly identical code for each different parameter count, the actual idea was to generate the still not executed job as a such zero parameter procedure of same type for all cases.
Still, I do not find a way how to construct or modify a function pointer inside a function; 'typecasting' in some way to Evaluator does not seem practicable, does it??
Again, thanks a lot, and Happy Easter... :-)
I think you're looking for std::bind. The name std::bind is new, previously it was part of Boost.
#include <functional>
std::function<A (void)> curry(A (*fn)(B), B b)
{
return std::bind(fn, b);
}
Without C++11 it could work like this:
typedef A(*Func)(B);
struct Evaluator {
Func f;
B b;
A operator()() const
{ return f(b); }
};
Evaluator eval(Func f, B b) {
Evaluator w;
w.f = f;
w.b = b;
return w;
}
That's essentially what std::bind is doing, so use std::bind if you can.
Today I was doing some catch-up on c++11 (as we have not moved on yet). One of the reasons to switch as stated by a lot of people seems to be lambda expressions. I am still unsure on how they offer something new.
For instance using c++11:
#include <iostream>
int main()
{
auto func = [] () { std::cout << "Hello world" << std::endl; };
func();
}
seems to be very similar to:
#include <iostream>
#define FUNC( )\
do { std::cout << "Hello world" << std::endl; } while(0)
int main()
{
FUNC();
}
What would lambda expressions offer me that I can't currently already do?
http://msdn.microsoft.com/en-us/library/vstudio/dd293608.aspx sums up the main points and more on the subject in great detail. Here is the salient excerpt:
A lambda combines the benefits of function pointers and function
objects and avoids their disadvantages. Like a function objects, a
lambda is flexible and can maintain state, but unlike a function
object, its compact syntax doesn't require a class definition. By
using lambdas, you can write code that's less cumbersome and less
prone to errors than the code for an equivalent function object.
There are examples on the site showing more differences and comparisons.
Also...conventional wisdom is never use macros in C++:
http://scienceblogs.com/goodmath/2007/12/17/macros-why-theyre-evil/
A less obvious benefit of lambdas when used with the standard algorithms is that the programmer is not required to think of a name for the lambda function, and naming things is considered to be a difficult task in programming.
Additionally, the code executed via the standard algorithms is often used to invoke a member function(s) on each object in the supplied range, with the name of the functor, or function, often just parroting the name of the member function being invoked and adding nothing to readability of the code. Contrived example:
struct object
{
void execute() const {}
};
void run_execute(object const& o) { o.execute(); }
std::vector<object> v;
std::for_each(v.begin(), v.end(), run_execute);
std::for_each(v.begin(), v.end(), [](object const& o) { o.execute(); });
Admittedly this is a minor benefit but still pleasant.
From the wikipedia article about Lambda functions and expressions:
users will often wish to define predicate functions near the place
where they make the algorithm function call. The language has only one
mechanism for this: the ability to define a class inside of a
function. ... classes defined in functions do not permit them to be used in templates
Does this mean that use of nested structure inside function is silently deprecated after C++0x lambda are in place ?
Additionally, what is the meaning of last line in above paragraph ? I know that nested classes cannot be template; but that line doesn't mean that.
I'm not sure I understand your confusion, but I'll just state all the facts and let you sort it out. :)
In C++03, this was legal:
#include <iostream>
int main()
{
struct func
{
void operator()(int x) const
{
std::cout << x << std::endl;
}
};
func f; // okay
f(-1); // okay
for (std::size_t i = 0; i < 10; ++i)
f(i) ; // okay
}
But if we tried doing this, it wasn't:
template <typename Func>
void exec(Func f)
{
f(1337);
}
int main()
{
// ...
exec(func); // not okay, local classes not usable as template argument
}
That left us with an issue: we want to define predicates to use for this function, but we can't put it in the function. So we had to move it to whatever outer scope there was and use it there. Not only did that clutters that scope with stuff nobody else needed to know about, but it moved the predicate away from where it's used, making it tougher to read the code.
It could still be useful, for the occasional reused chunk of code within the function (for example, in the loop above; you could have the function predicate to some complex thing with its argument), but most of the time we wanted to use them in templates.
C++0x changes the rules to allow the above code to work. They additionally added lambdas: syntax for creating function objects as expressions, like so:
int main()
{
// same function as above, more succinct
auto func = [](int x){ std::cout << x << std::endl; };
// ...
}
This is exactly like above, but simpler. So do we still have any use for "real" local classes? Sure. Lambda's fall short of full functionality, after all:
#include <iostream>
template <typename Func>
void exec(Func func)
{
func(1337);
}
int main()
{
struct func
{
// note: not possible in C++0x lambdas
void operator()(const char* str) const
{
std::cout << str << std::endl;
}
void operator()(int val) const
{
std::cout << val << std::endl;
}
};
func f; // okay
f("a string, ints next"); // okay
for (std::size_t i = 0; i < 10; ++i)
f(i) ; // okay
exec(f); // okay
}
That said, with lambda's you probably won't see local classes any more than before, but for completely different reasons: one is nearly useless, the other is nearly superseded.
Is there any use case for class inside function after introduction of lambda ?
Definitely. Having a class inside a function is about:
localising it as a private implementation detail of the code intending to use it,
preventing other code using and becoming dependent on it,
being independent of the outer namespace.
Obviously there's a threshold where having a large class inside a function harms readability and obfuscates the flow of the function itself - for most developers and situations, that threshold is very low. With a large class, even though only one function is intended to use it, it may be cleaner to put both into a separate source file. But, it's all just tuning to taste.
You can think of this as the inverse of having private functions in a class: in that situation, the outer API is the class's public interface, with the function kept private. In this situation, the function is using a class as a private implementation detail, and the latter is also kept private. C++ is a multi-paradigm language, and appropriately gives such flexibility in modelling the hierarchy of program organisation and API exposure.
Examples:
a function deals with some external data (think file, network, shared memory...) and wishes to use a class to represent the binary data layout during I/O; it may decide to make that class local if it only has a few fields and is of no use to other functions
a function wants to group a few items and allocate an array of them in support of the internal calculations it does to derive its return value; it may create a simple struct to wrap them up.
a class is given a nasty bitwise enum, or perhaps wants to reinterpret a float or double for access to the mantisa/exponent/sign, and decides internally to model the value using a struct with suitable-width bitfields for convenience (note: implementation defined behaviours)
classes defined in functions do not permit them to be used in templates
I think you commented that someone else's answer had explained this, but anyway...
void f()
{
struct X { };
std::vector<X> xs; // NOPE, X is local
}
Defining structures inside functions was never a particularly good way to deal with the lack of predicates. It works if you have a virtual base, but it's still a pretty ugly way to deal with things. It might look a bit like this:
struct virtual_base {
virtual void operator()() = 0;
};
void foo() {
struct impl : public virtual_base {
void operator()() { /* ... */ }
};
register_callback(new impl);
}
You can still continue to use these classes-inside-functions if you want of course - they're not deprecated or crippled; they were simply restricted from the very start. For example, this code is illegal in versions of C++ prior to C++0x:
void foo() {
struct x { /* ... */ };
std::vector<x> y; // illegal; x is a class defined in a function
boost::function<void()> z = x(); // illegal; x is used to instantiate a templated constructor of boost::function
}
This kind of usage was actually made legal in C++0x, so if anything the usefulness of inner classes has actually be expanded. It's still not really a nice way of doing things most of the time though.
Boost.Variant.
Lambdas don't work with variants, as variants need objects that have more than one operator() (or that have a templated operator()). C++0x allows local classes to be used in templates now, so boost::apply_variant can take them.
As Tony mentioned, a class inside a function is not only about predicates. Besides other use cases, it allows to create a factory function that creates objects confirming to an interface without exposing the implementing class. See this example:
#include <iostream>
/* I think i found this "trick" in [Alexandrescu, Modern C++ Design] */
class MyInterface {
public:
virtual void doSomethingUseful() = 0;
};
MyInterface* factory() {
class HiddenImplementation : public MyInterface {
void doSomethingUseful () {
std::cout << "Hello, World!" << std::endl;
}
};
return new HiddenImplementation();
}
int main () {
auto someInstance = factory();
someInstance->doSomethingUseful();
}