Provide documentation for C++ class exposed via Rcpp - rcpp

Suppose I have a small C++ class where I have inlined all the functions (and attempted to document via Roxygen per [Section 3.4]):
class HelloWorld {
private:
int count;
public:
//' the constructor for the class
HelloWorld() : count(0) {}
//' my magical function
//' #param arg the integer to add
//' #return the magical result
int example(int arg) { return 2*count+arg; }
};
I can expose this class to Rcpp:
RCPP_MODULE(helloworld){
Rcpp::class_<HelloWorld>("HelloWorld")
.constructor()
.method("example", &HelloWorld::example, "A magical function.");
};
However, the generated R/RcppExports.R from Rcpp.package.skeleton() looks like
#' the constructor for the class
NULL
#' Inserts an entry into the dictionary
#' #param arg the integer to add
#' #return the magical result
NULL
I'm sure I'm just missing something obvious. Any ideas?

Related

MQL4 struct containing adress to other structs

I need to code something like that but I don't know the right syntax in the second structure to have fields containing address to structure of first type.
struct ConditionSet
{
int CondsNbr; // Number of cond-s in the set
bool TabConds [MaxConditions];
string TabCondsLabel [MaxConditions];
int CandleNum [MaxConditions];
bool ExitCondition;
int int1, int2, int3, int4, int5; // user integers
double d1, d2, d3,d4, d5; // user doubles
};
struct Transaction
{
string Strategie_name;
string Symbol;
bool BuyReady;
bool SellReady;
bool BuyRunning;
bool SellRunning;
ConditionSet & conditionsAchat; // HERE, THIS IS NOT A CORRECT SYNTAX
ConditionSet & conditionsVente; // HERE, THIS IS NOT A CORRECT SYNTAX
int ticketAchat;
int ticketVente;
};
If a structure contains variables of the string type and/or object of a dynamic array, the compiler assigns an implicit constructor to such a structure. This constructor resets all the structure members of string type and correctly initializes objects of the dynamic array.
Object Pointers
In MQL4, there is a possibility to dynamically create objects of complex type. This is done by the new operator, which returns a descriptor of the created object. Descriptor is 8 bytes large. Syntactically, object descriptors in MQL4 are similar to pointers in C++.
MyObject* hobject= new MyObject();
In contrast to C++, the hobject variable from example above is not a pointer to memory, but rather an object descriptor. Furthermore, in MQL5 all objects in function parameters must be passed by reference.
//+------------------------------------------------------------------+
//| Objects are always passed by reference |
//+------------------------------------------------------------------+
void PrintObject(Foo &object)
{
Print(__FUNCTION__,": ",object.m_id," Object name=",object.m_name);
}
//+------------------------------------------------------------------+
//| Passing an array of objects |
//+------------------------------------------------------------------+
void PrintObjectsArray(Foo &objects[])
{
int size=ArraySize(objects);
for(int i=0;i<size;i++)
{
PrintObject(objects[i]);
}
}
//+------------------------------------------------------------------+
//| Passing an array of pointers to object |
//+------------------------------------------------------------------+
void PrintPointersArray(Foo* &objects[])
{
int size=ArraySize(objects);
for(int i=0;i<size;i++)
{
PrintObject(objects[i]);
}
}
//+------------------------------------------------------------------+
class Foo
{
public:
string m_name;
int m_id;
static int s_counter;
//--- constructors and desctructors
Foo(void){Setup("noname");};
Foo(string name){Setup(name);};
~Foo(void){};
//--- initializes object of type Foo
void Setup(string name)
{
m_name=name;
s_counter++;
m_id=s_counter;
}
};
//+------------------------------------------------------------------+
int Foo::s_counter=0;
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare an object as variable with its automatic creation
Foo foo1;
//--- variant of passing an object by reference
PrintObject(foo1);
//--- declare a pointer to an object and create it using the 'new' operator
Foo *foo2=new Foo("foo2");
//--- variant of passing a pointer to an object by reference
PrintObject(foo2); // pointer to an object is converted automatically by compiler
//--- declare an array of objects of type Foo
Foo foo_objects[5];
//--- variant of passing an array of objects
PrintObjectsArray(foo_objects); // separate function for passing an array of objects
//--- declare an array of pointers to objects of type Foo
Foo *foo_pointers[5];
for(int i=0;i<5;i++)
{
foo_pointers[i]=new Foo("foo_pointer");
}
//--- variant of passing an array of pointers
PrintPointersArray(foo_pointers); // separate function for passing an array of pointers
//--- it is obligatory to delete objects created as pointers before termination
delete(foo2);
//--- delete array of pointers
int size=ArraySize(foo_pointers);
for(int i=0;i<5;i++)
delete(foo_pointers[i]);
//---
}
//+------------------------------------------------------------------+
Keyword this
A variable of class type (object) can be passed both by reference and by pointer. As well as reference, the pointer allows having access to an object. After the object pointer is declared, the new operator should be applied to it to create and initialize it.
The reserved word this is intended for obtaining the reference of the object to itself, which is available inside class or structure methods. this always references to the object, in the method of which it is used, and the expression GetPointer(this) gives the pointer of the object, whose member is the function, in which call of GetPointer() is performed. In MQL4 functions can't return objects, but they can return the object pointer.
Thank you for replying.
After moving the Foo class to the top of the source, and adding the strict property, I could compile your source.
I don't understand the line
int Foo::s_counter=0;
What it does ?
I'm thinking how classes could resolve my problem but it's not easy.
Janfi

PHPCS rule for type hinting

Is there a rule to check all functions for type hinting?
/**
* Set the part name.
*
* #param string $name The part name.
*/
public function setName(string $name) : void
{
$this->name = $name;
}
So for example it has to have a type in front of the argument and the function has to have a specified return type.
2019 update - even Smarter
In time, my previous answer - TypeHintDeclarationSniff - has shown as very buggy. To be specific:
public function anotherMethod(int $value)
{
// $value is known integer
$this->someMethod($value);
}
/**
* #param string $value
*/
-private function someMethod($value)
+private function someMethod(string $value) // here should be "int"
{
}
Missed cases:
public function getItems() // here should be "array"
{
return ['Statie', 'EasyCodingStandard', 'Rector'];
}
Or:
public function getResult() // here should be "float"
{
if (true) {
return 5.2;
}
return 5.3;
}
Or even breaks the code with parent type in /vendor. Why? Because it's based on strings and token, not a static analysis of the code.
This made many people very angry, after I recommended them this sniff. Obviously.
How to do it Better?
I wrote a tool called Rector (https://github.com/rectorphp/rector), that takes into account other variables and other classes and their types.
That way you can complete type declarations to a code without any #param or #return annotations.
How to use It?
Install:
composer require vendor/bin/rector
Setup rector.yaml config:
# rector.yaml
services:
Rector\Php\Rector\FunctionLike\ParamTypeDeclarationRector: ~
Rector\Php\Rector\FunctionLike\ReturnTypeDeclarationRector: ~
Use:
vendor/bin/rector process src --dry-run # preview
vendor/bin/rector process src # change
That's it!
Read Behind the Scenes
How to Complete Type Declarations without Docblocks with Rector
The Rocket Science Behind Migration of Docblock Types to PHP Typehints
Initial answer:
You can use TypeHintDeclarationSniff from Slevomat/CodingStandard for this.
I use it for over a year and it works perfectly.

C++11 thread pool - tasks with input parameters

I am trying to use a simple thread pool example from the book of Anthony Williams "C++ Concurrency in Action". I have even found the code here (the class thread_pool) in one of the posts:
Synchronizing tasks
but I have a different question. I would like to submit a task (a member function) to the queue with the following signature:
class A;
class B;
bool MyClass::Func(A*, B*);
How would I need to change the thread_pool class, or how do I pack my function in some void F(), which is assumed to be used as a task in this example?
Here is the most relevant part of the class for me (for the details please see the link above):
class thread_pool
{
thread_safe_queue<std::function<void()> work_queue; // bool MyClass::Func(a,b) ??
void worker_thread() {
while(!done) {
std::function<void()> task;
if(work_queue.try_pop(task)) {
task(); // how should my function MyClass::Func(a,b) be called here?
}
else {
std::this_thread::yield();
}
}
}
// -- Submit a task to the thread pool
template <typename FunctionType>
void submit(FunctionType f) {
work_queue.push(std::function<void()>(f)); // how should bool MyClassFunc(A*, B*) be submitted here
}
}
And finally, how can I call the submit Function in my code?
Thank you very much for your help (unfortunatelly I am not very experienced yet in using all the C++11 features, which is probably also why I need help here, but an answer to this question would be something to start with :)).
You have to bind the parameters to a value when you insert a task into the queue. That means that you have to create a wrapper for your function that stores the values for this and the values for the two function parameters. There are many ways to do this, e.g. lambda functions or std::bind.
work_queue.push_back( [obj, a, b]() {obj->Func(a,b)} );
work_queue.push_back( std::bind(&MyClass::Func, obj, a, b) );
Your submit function must take these parameters and create the binding, e.g.
template<typename F, typename... Args>
void submit(F f, Args&&... args) {
work_queue.push_back( std::bind(f, std::forward<Args>(args)...) );
}
It may be convenient to create a special overload for member functions and objects.
I've written something that does something (very) similar to this before. I'll post the code here and you can have a look. GenCmd is the function wrapper. The queue looks like this, and is used/defined in Impl (code omitted). You only need to look at implementation of GenCmd, as this contains the necessary work.
ConcurrentQueue<std::unique_ptr<Cmd>> cqueue_;
I've wrapped std::function<> to be polymorphic in queue. std_utility contains make_index_sequence, that is used to extract values from a tuple (google make_index_sequence to find an implementation somewhere if this is not already part of your std library).
#include <functional>
#include <memory>
#include <iostream>
#include <utility>
#include <boost/noncopyable.hpp>
class CmdExecutor : public boost::noncopyable
{
public:
CmdExecutor(std::ostream& errorOutputStream);
~CmdExecutor();
template <class Receiver, class ... FArgs, class ... CArgs >
void process(Receiver& receiver, void (Receiver::*f)(FArgs...), CArgs&&... args)
{
process(std::unique_ptr<Cmd>(new GenCmd<void(Receiver,FArgs...)>(f, receiver, std::forward<CArgs>(args)...)));
}
private:
class Cmd
{
public:
virtual void execute() = 0;
virtual ~Cmd(){}
};
template <class T> class GenCmd;
template <class Receiver, class ... Args>
class GenCmd<void(Receiver, Args...)> : public Cmd
{
public:
template <class FuncT, class ... CArgs>
GenCmd(FuncT&& f, Receiver& receiver, CArgs&&... args)
: call_(std::move(f)),
receiver_(receiver),
args_(args...)
{
}
//We must convert references to values...
virtual void execute()
{
executeImpl(std::make_index_sequence<sizeof...(Args)>{});
}
private:
template <std::size_t ... Is>
void executeImpl(std::index_sequence<Is...>)
{
// We cast the values in the tuple to the original type (of Args...)
call_(receiver_, static_cast<Args>(std::get<Is>(args_))...);
}
std::function<void(Receiver&, Args...)> call_;
Receiver& receiver_;
// NOTE:
// References converted to values for safety sake, as they are likely
// to not be around when this is executed in other context.
std::tuple<typename std::remove_reference<Args>::type...> args_;
};
void process(std::unique_ptr<Cmd> command);
class Impl;
Impl* pimpl_;
};
It's basically used as follows:
...
CmdExecutor context_;
...
void MyClass::myFunction()
{
ArgX x;
ArgY y;
context_.process(*this, &MyClass::someFunction, x, y);
}
You can see from this that process does the wrapping of member function type and converts it to the underlying type for storage on queue. This allows for multiple argument types. I've opted for using runtime polymorphism to store the function types, hence the GenCmd derivative.
Note: If the invoked function receives an rvalue (Arg&&), the stored type is casted to the original type, therefore causing a move, and rendering the applicable command argument (which would only be invoked once) empty (that's the intent, at least - untested...)

In Haxe, how do you pass Enum values in functions, and then convert them to Strings within the function?

I can't seem to get this working, but I'd be surprised if it wasn't possible in Haxe.
I'm trying to pass a couple of Enum values defined in my game to a function, so that it can then concatenate them as String types and pass that to other functions.
Example:
// In a general Entity class:
public override function kill():Void {
messages.dispatchCombined(entityType, ListMessages.KILLED);
super.kill();
}
And in my Messages.hx class:
package common;
import msignal.Signal.Signal1;
/**
* A Message / Event class using Signals bound to String names.
* #author Pierre Chamberlain
*/
class Messages{
var _messages:MessagesDef;
public function new() {
_messages = new MessagesDef();
}
public function add(pType:String, pCallback:FuncDef) {
if (_messages[pType] == null) {
_messages[pType] = new Signal1<Dynamic>();
}
var signals = _messages[pType];
signals.add( pCallback );
}
public function dispatch(pType:String, pArg:Dynamic):Bool {
var signals = _messages[pType];
if (signals == null) return false;
signals.dispatch(pArg);
return true;
}
//Compiler doesn't like passing enums :(
public inline function addCombined(pSource:Enum, pEvent:Enum, pCallback:FuncDef) {
add( combine(pSource, pEvent), pCallback );
}
public inline function dispatchCombined(pSource:Enum, pEvent:Enum, pArg:Dynamic):Bool {
return dispatch( combine(pSource, pEvent), pArg);
}
//How can I just pass the enum "names" as strings?
static inline function combine(a:Enum, b:Enum):String {
return String(a) + ":" + String(b);
}
}
typedef MessagesDef = Map<String, Signal1<Dynamic>>;
typedef FuncDef = Dynamic->Void;
Note how addCombined, dispatchCombined and combine expect an "Enum" type, but in this case I'm not sure if Haxe actually expects the entire Enum "class" to be passed (ie: ListMessages instead of ListMessages.KILLED) or if a value should work. Anyways, compiler doesn't like it - so I'm assuming another special Type has to be used.
Is there another way to go about passing enums and resolving them to strings?
I think you need EnumValue as parameter type (if it is only for enum values), and use Std.String to convert to String values.
static inline function combine(a:EnumValue, b:EnumValue):String {
return Std.string(a) + ":" + Std.string(b);
}
Of course that can be written smaller using String interpolation:
static inline function combine(a:EnumValue, b:EnumValue):String {
return '$a:$b';
}
Of course that can be 'more dynamic' using type parameters:
static inline function combine<A, B>(a:A, b:B):String {
return '$a:$b';
}
There is totally no need to use Dynamic as suggested. If you use Dynamic, you basically turn off the type system.
live example:
http://try.haxe.org/#a8844
Use Dynamic instead of Enum or pass them as Strings right away since you can always convert to enum from String if you need it later.
Anyway pass the enum as enum:Dynamic and then call Std.string(enum);
EDIT: Using EnumValue is definitely better approach than Dynamic, I use Dynamic in these functions because I send more than just Enums there and I am not worried about type safety in that case.

Error assigning value to a static variable

In this piece of code I don't know why the compiler doesn't let me assign the value 0 to variable x. I highlighted the line that cause the problem.
class List{
private:
int p;
public:
static int x;
void total();
};
void List::total(List *a){
x + = a -> p;
cout<<x;
getch();
x=0; // problem here
}
I also noticed that if I write int List::sum=0 before the function body, program works just fine. I just don't understand why.
I appreciate any help!
You have declared the static in your class but have not defined a variable for it.
class List{
private:
int p;
public:
static int x; // this is just a declaration
void total();
};
You need to define it, normally in the associated cpp file:
List::x = 0; // define variable and initialise
Quoting from here:
9.4.2 Static data members
The declaration of a static data member in its class definition is
not a definition and may be of an incomplete type other than
cv-qualified void. The definition for a static data member
shall appear in a namespace scope enclosing the member's class
definition. In the defi- nition at namespace scope, the name of the
static data member shall be qualified by its class name using the ::
operator. The initializer expression in the definition of a
static data member is in the scope of its class
(basic.scope.class).
The operator += tries to increase the value of x. You need to initialize x before using it.

Resources