What situation uses this syntax: thing.Foo().Bar(this) - c++11

Can someone show me an example of where this syntax would show up in code?
thing.Foo().Bar(this)
From the looks of it, I see an object that calls a function that calls another function?
I obviously don't know how it works. If you have the slightest idea, I would appreciate a suggestion. Thanks!

This is one of many possible scenarios:
struct somethingelse
{
void SomeOtherMethod()
{
thing.Foo().Bar(this);
}
};
struct foo
{
void Bar(somethingelse *pSomethingElse);
};
struct thing
{
foo &Foo() {return m_foo;}
foo m_foo;
};
What makes this a bit unusual is that the naming convention for the class and method naming is the opposite of the de-facto one in which classes are capitalised and methods camel-cased.

This code could be found in any non-static member function of a class. The Foo() function of thing returns an object of a class with a member function Bar that takes a pointer to the current object (this) as argument.

Related

safely passing a callback from managed code to native code

I have a lot of native classes that accept some form of callbacks, usually a boost::signals2::slot-object.
But for simplicity, lets assume the class:
class Test
{
// set a callback that will be invoked at an unspecified time
// will be removed when Test class dies
void SetCallback(std::function<void(bool)> callback);
}
Now I have a managed class that wraps this native class, and I would like to pass a callback method to the native class.
public ref class TestWrapper
{
public:
TestWrapper()
: _native(new Test())
{
}
~TestWrapper()
{
delete _native;
}
private:
void CallbackMethod(bool value);
Test* _native;
};
now usually what I would do is the following:
Declare a method in the managed wrapper that is the callback I want.
Create a managed delegate object to this method.
Use GetFunctionPointerForDelegate to obtain a pointer to a function
Cast the pointer to the correct signature
Pass the pointer to the native class as callback.
I also keep the delegate alive since I fear it will be garbage collected and I will have a dangling function pointer (is this assumption correct?)
this looks kind of like this:
_managedDelegateMember = gcnew ManagedEventHandler(this, &TestWrapper::Callback);
System::IntPtr stubPointer = Marshal::GetFunctionPointerForDelegate(_managedDelegateMember);
UnmanagedEventHandlerFunctionPointer functionPointer = static_cast<UnmanagedEventHandlerFunctionPointer >(stubPointer.ToPointer());
_native->SetCallback(functionPointer);
I Would like to reduce the amount of code and not have to perform any casts nor declare any delegate types. I want to use a lambda expression with no delegate.
This is my new approach:
static void SetCallbackInternal(TestWrapper^ self)
{
gcroot<TestWrapper^> instance(self);
self->_native->SetCallback([instance](bool value)
{
// access managed class from within native code
instance->Value = value;
}
);
}
Declare a static method that accepts this in order to be able to use C++11 lambda.
Use gcroot to capture the managed class in the lambda and extend its lifetime for as long as the lambda is alive.
No casts, no additional delegate type nor members, minimal extra allocation.
Question:
Is this approach safe? I'm fearing I'm missing something and that this can cause a memory leak / undefined behavior in some unanticipated scenario.
EDIT:
this approach leads to a MethodAccessException when the lambda calls a private method of its managed wrapper class. seems like this method must at least be internal.
I think that you should not be using gcroot but a shared pointer. Shared pointer are made to keep an object alive as long as someone is using it.
You should also use a more c++ style in your whole code by replacing raw pointer with smart pointer and template instead of std::function (a lambda can be stored in a compile time type).
For example using the code you posted :
class Test
{
// set a callback that will be invoked at an unspecified time
// will be removed when Test class dies
template <class T>
void SetCallback(T callback); // Replaced std::function<void(bool)> with T
}
public ref class TestWrapper
{
public:
TestWrapper()
: _native()
{}
private:
void CallbackMethod(bool value);
std::unique_ptr<Test> _native; // Replaced Test* with std::unique_ptr<Test>
};
After replacing the old method with this new method all over my code base, I can report that it is safe, more succinct, and as far as I can tell, no memory leaks occur.
Hence I highly recommend this method for passing managed callbacks to native code.
The only caveats I found were the following:
Using lambda expressions forces the use of a static method as a helper for the callback registration. This is kinda hacky. It is unclear to me why the C++-CLI compiler does no permit lambda expressions within standard methods.
The method invoked by the lambda must be marked internal so to not throw MethodAccessException upon invocation. This is sort of make sense as it is not called within the class scope itself. but still, delegates / lambdas with C# don't have that limitation.

Inferencing the typename of 'this' in a virtual method

I am aware of the lack of reflection and basic template mechanics in C++ so the example below can't work. But maybe there's a hack to achieve the intended purpose in another way?
template <typename OwnerClass>
struct Template
{
OwnerClass *owner;
};
struct Base
{
virtual void funct ()
{
Template <decltype(*this)> temp;
// ...
}
};
struct Derived : public Base
{
void whatever ()
{
// supposed to infer this class and use Template<Derived>
// any chance some macro or constexpr magic could help?
funct();
}
};
In the example, Derived::whatever() calls virtual method Base::funct() and wants it to pass its own class name (Derived) to a template. The compiler complains "'owner' declared as a pointer to a reference of type 'Base &'". Not only does decltype(*this) not provide a typename but a reference, the compiler also can't know in advance that funct is called from Derived, which would require funct() to be made a template.
If funct() was a template however, each derived class needs to pass its own name with every call, which is pretty verbose and redundant.
Is there any hack to get around this limitation and make calls to funct() infer the typename of the calling class? Maybe constexpr or macros to help the compiler infer the correct type and reduce verbosity in derived classes?
You should use CRTP Pattern (Curiously Recurring Template Pattern) for inheritance.
Define a base class:
struct CBase {
virtual ~CBase() {}
virtual void function() = 0;
};
Define a prepared to CRTP class:
template<typename T>
struct CBaseCrtp : public CBase {
virtual ~CBaseCrtp() {}
void function() override {
using DerivedType = T;
//do stuff
}
};
Inherit from the CRTP one:
struct Derived : public CBaseCrtp<Derived> {
};
It should work. The only way to know the Derived type is to give it to the base!
Currently, this can't be done. Base is a Base and nothing else at the time Template <decltype(*this)> is instantiated. You are trying to mix the static type system for an inheritance hierarchy inherently not resolved before runtime. This very same mechanism is the reason for not calling virtual member functions of an object during its construction.
At some point, this limitation might change in the future. One step towards this is demonstrated in the Deducing this proposal.

Mocking struct argument

FULL DISCLOSURE: This is probably really dumb, but I'm new to Go and haven't used statically-typed languages in years.
I have a function that looks like this:
func Foo(bar *bar.BarStruct) {
// do stuff with bar
}
In this example, bar is a third-party package and *bar.BarStruct is a pointer to a struct.
I would like to write a test for the Foo function while stubbing out bar.BarStruct struct. How would I stub out *bar.BarStruct?
In JavaScript for example, I would just do something like this
test('does a Foo', () => {
const mockBarStruct = {
someProp: 123
}
Foo(mockBarStruct)
// rest of test
})
What's the equivalent way to stub a struct in Go?
If you had Foo take an interface instead of a struct pointer, the in tested you could pass a mock or fake struct that implements that interface.
There are some mocking libraries but because Golang doesn’t allow runtime type writing, they run compile-time and output code.
Hope that helps!

is it possible to have boost::optional of a class and call its member functions?

I tried using boost optional and it works nice, but I cant find a way to call the member functions of the wrapped type. Is that by design or? I guess so because calling member funcs of unitialized boost::optional variable would be bad, but I want to be 100% sure.
class test
{
int test_method()
{
return 1984;
}
};
test tst;
boost::optional<test> get_test()
{
boost::optional<test> result(tst);
return result;
}
// main
boost::optional <test> ret_val= get_test();
int x=ret_val.test_method();
‘class boost::optional ANGLE_BRACKET test ANGLE_BRACKET ’ has no member named ‘test_method’
Try using ret_val->test_method() instead; operator-> can access the contained object in a boost::optional. Note that you need to ensure that the optional is not empty before you do that.

Code Brain "Teaser" -- but not really

I'm just curious to see what you guys think about this. I heard a bunch of answers passed around the office and I want to see if you guys can have possibly a better one.
Question:
You have two functions outlined below:
function one()
{
A();
B();
C();
}
function two()
{
A();
D();
C();
}
How would you re-write this (anything counts, you could create classes, variables, other methods, anything), to reduce code duplication?
Each of the methods called changes variables that the other functions need to use. Methods A() B() and C() are already defined.
Not all languages will support this approach, and the syntax of passing a function may vary between those that do, but the concept would be:
function one()
{
refactored(B);
}
function two()
{
refactored(D);
}
function refactored(middleMan)
{
A();
middleMan();
C();
}
There is no code duplication here. It looks fine.
Each of the methods called changes variables that the other functions need to use.
I would start by refactoring the entire class to use proper OOP.
There are a number of ways to refactor that code; which I would use depends on the specific application, as it may mean that I need to reconsider things at a higher level, e.g. redefine classes, or at worst review the entire application design because the duplication means I missed some key relationship.
If your functions one() and two() are really three-liners as in the example, I wouldn't rewrite anything. You would loose readability and make the code much harder to understand for the next guy.
If the calls to A() and C() are actually larger blocks of code...
- define a base class with abstract method X() and a concrete
function any()
{
A();
X();
C();
}
define a class One where X() is implemented by B()
define a class Two where X() is implemented by D()
Here's one option.
function (triggerA, triggerB, triggerC, triggerD)
{
A(triggerA);
B(triggerB);
C(triggerC);
D(triggerD);
}
This way you're only calling one function to do it all, and skips whatever you don't need/want to do.
If you have closures, lambdas etc. available, you could write
function one()
{
three(B)
}
function two()
{
three(D);
}
function three(middle)
{
A();
middle();
C();
}
You could (but probably shouldn't) make a class where A() is the constructor and C() is the destructor, and have one() and two() be methods of the class calling B() and D() respectively.
I said you probably shouldn't because OOP should be used to write code that makes sense and not for obscure optimization reasons.
In C++ this is usually accomplished with RAII if the context makes sense... this pattern is usually A() = some init function, C() = some de-init function. There's usually also a context associated that's being initialized or destroyed as well.
class bar
{
bar() {
A();
}
~bar() {
C();
}
};
void one()
{
bar barvar;
B();
}
void two()
{
bar barvar;
D();
}

Resources