Cast template class pointer to pointer of a template class within - pointers

In short:
There's a templatized class object "queue"
Another templatized object "task" contains a queue as first member (address of task will point to queue object)
An observer function receives only addresses to queues and calls queue's member function do_something(). However, one of those passed pointers is of type task*. This address will at the same time point to an object of type task and queue, however I want to keep this implementation detail hidden from the user.
Code:
#include <iostream>
template <int I>
struct queue
{
int i_ = I;
void do_something() {
std::cout << "do_something() called!" << std::endl;
}
};
queue<1> hello1;
queue<2> hello2;
template <int J>
struct task
{
queue<3> hello3;
int j_ = J;
};
task<1> task1;
template <typename... Ts>
void observe(Ts... Args)
{
(( static_cast<queue/* can't really specify template? */*>(Args)->do_something(), void()), ... );
}
int main()
{
observe(&hello1, &hello2, &task1);
}
I get this error:
<source>: In function 'void observe(Ts ...)':
<source>:29:20: error: missing template arguments after 'queue'
(( static_cast<queue/* can't really specify template? */*>(Args)->do_something(), void()), ... );
^~~~~
<source>:5:8: note: 'template<int I> struct queue' declared here
struct queue
^~~~~
<source>:29:96: error: operand of fold expression has no unexpanded parameter packs
(( static_cast<queue/* can't really specify template? */*>(Args)->do_something(), void()), ... );
^~~
Compiler returned: 1
Now my question is: Can I somehow cast the pointer to a pointer to queue<X>* so the calls to do_something() resolve correctly to a queue object? Or is there another way to achieve the same?

Related

RcppParallel worker with additional arguments

This is my first try with the RcppParallel package and I have to work with C++17 (Ubuntu)
I tried to stay close to the ParallelFor example of the developers site, but I need an additional (non-iterative) argument for the worker threshold.
This is the my current code
struct ReplaceWorker : public Worker
{
// source matrix
const RMatrix<double> input;
// destination matrix
RMatrix<double> output;
// threshold
double th;
// initialize with source and destination
ReplaceWorker(const NumericMatrix input, NumericMatrix output, double threshold)
: input(input), output(output), th(threshold) {}
// replace function
template<typename T>
double replacer(const T &x){
if(x < th){
return(0);
} else {
return(1);
}
}
// take the square root of the range of elements requested
void operator()(std::size_t begin, std::size_t end) {
std::transform(input.begin() + begin,
input.begin() + end,
output.begin() + begin,
replacer);
}
};
However I always end up with the same compilation errors:
usr/include/c++/7/bits/stl_algo.h:4295:5: note: candidate: template<class _IIter, class _OIter, class _UnaryOperation> _OIter std::transform(_IIter, _IIter, _OIter, _UnaryOperation)
transform(_InputIterator __first, _InputIterator __last,
^~~~~~~~~
/usr/include/c++/7/bits/stl_algo.h:4295:5: note: template argument deduction/substitution failed:
network_edge_strength.cpp:173:28: note: couldn't deduce template parameter ‘_UnaryOperation’
replacer);
^
/usr/include/c++/7/bits/stl_algo.h:4332:5: note: candidate: template<class _IIter1, class _IIter2, class _OIter, class _BinaryOperation> _OIter std::transform(_IIter1, _IIter1, _IIter2, _OIter, _BinaryOperation)
transform(_InputIterator1 __first1, _InputIterator1 __last1,
^~~~~~~~~
/usr/include/c++/7/bits/stl_algo.h:4332:5: note: template argument deduction/substitution failed:
network_edge_strength.cpp:173:28: note: candidate expects 5 arguments, 4 provided
replacer);
^
Any suggestions, how to fix this or alternatives, how to make it run with the required threshold parameter?
replacer is a function template, not a function, which means it cannot be used as a function object unless a specific instantiation is used, as otherwise template argument deduction fails.
Additionally, as a member function, it would require an implicit object parameter to be callable.
You could use a generic lambda expression instead:
std::transform(/* [...] */, [this] (const auto& x) { return replacer(x); });
This way, even if replacer is overloaded or is a function template, this will work.
Alternatively, remove replacer altogether, and use a lambda expression directly:
std::transform(/* [...] */, [this] (const auto& x) { return x < th ? 0 : 1; });

Using valgrind - "Invalid read of size 1" for strlen

I'm trying to write code that sets the name of a Student object to a new name, but I'm coming across memory leak errors when creating a character array. I assume it has to do with /0 at the end of the array and isn't terminating properly, but I don't know how to properly fix this. Thanks for the help.
#include "student.h"
#include <string>
#include <cstring>
#include <iostream>
using namespace std;
Student::Student(const char * const name, int perm) {
this->setName(name);
this->setPerm(perm);
}
int Student::getPerm() const {
return this->perm;
}
const char * const Student::getName() const {
return this->name;
}
void Student::setPerm(const int perm) {
this->perm = perm;
}
void Student::setName(const char * const newName) {
this->name = new char[strlen(newName)+1];
// this->name[srtlen(newName)+1] = '/0'; <---- My suggested fix, but doesn't work
strcpy(this->name,newName);
}
Student::Student(const Student &orig) {
this->setName(orig.getName());
this->setPerm(orig.getPerm());
}
Student::~Student() {
delete this->name;
this->perm = 0;
}
This is the valgrind error:
==13814== Invalid read of size 1
==13814== at 0x4C2BA12: strlen (vg_replace_strmem.c:454)
==13814== by 0x4F56FD6: UnknownInlinedFun (char_traits.h:267)
==13814== by 0x4F56FD6: std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&) (basic_string.h:456)
==13814== by 0x401ED8: Student::toString[abi:cxx11]() const (student.cpp:64)
==13814== by 0x401A46: main (testStudent00.cpp:14)
==13814== Address 0x5302e8 is not stack'd, malloc'd or (recently) free'd
==13814==
Your assumption that you needed to add the 0 terminator is wrong, strcpy() will do that for you. Your attempt of doing so adds the 0 terminator one byte past the space you allocated (remember, array indexes start at zero), and the syntax is also wrong, you would need to do:
this->name[strlen(newName)] = '\0';
However, to fix your memory leak You need to delete the previous string, like
void Student::setName(const char * const newName)
{
delete [] this->name;
this->name = new char[strlen(newName)+1];
strcpy(this->name,newName);
}
Student::Student(const Student &orig) :
name(0) {
this->setName(orig.getName());
this->setPerm(orig.getPerm());
}
Student::~Student() {
delete [] this->name;
this->perm = 0;
}
Now, for this to work, you also need to fix your constructor and copy constructor to initialize the name member, so it isn't an uninitialized pointer for the first call to the setName() function, and you need to add an assignment operator too, so you can properly handle assignments.
Student::Student(const char * const name, int perm) :
name(0)
{
this->setName(name);
this->setPerm(perm);
}
Student &operator=(const Student &orig) {
this->setName(orig.getName());
this->setPerm(orig.getPerm());
}
Also, consider using std::string instead of your current low level way of handling strings, that way you don't need to even implement a copy constructor, assignment operator and destructor for this class, nor deal with correctly managing memory.

Qt Meta System Call constructor with parameters

I know that I can use QMetaType to create an object without parameters.
Another possible option is to use QMetaObject and call newInstance. But I need to get QMetaObject from something.
I tried to use QMetaType::metaObjectForType, but it always returns null pointer (but QMetaType is able to create the object).
QMetaObject const* metaObject = QMetaType::metaObjectForType(id); // return null pointer
QObject* object = (QObject*)QMetaType::create(id); // create the object
QMetaObject const* metaObject = object->metaObject(); // return not-null pointer
UPDATE:
I think the question is why metaObjectForType does not work for me.
The class is registered with qRegisterMetaType, also Q_DECLARE_METATYPE and Q_OBJECT are applied.
First of all, to pass parameters to methods, you needs some kind of reflection framework beyond plain C++. With Qt, the obivous choice is Qt Meta Object system with it's QMetaObject, though then you must derive your classes for QObject. After that, you need to do two things:
1. make constructor invokable
Signals and slots are invokable by default, but any other method you want to invoke through the meta object system needs to be explicitly marked as such. Example myqobject.h:
#ifndef MYQOBJECT_H
#define MYQOBJECT_H
#include <QObject>
class MyQObject : public QObject
{
Q_OBJECT
public:
Q_INVOKABLE MyQObject(QObject *parent = 0); // tested with empty constructor in .cpp
};
#endif // MYQOBJECT_H
2. create your own mapping from class name string to the QMetaObject
QMetaType doc says: "any class or struct that has a public default constructor, a public copy constructor, and a public destructor can be registered." This rules out QObject, because they can't have copy constructors. You need to create your own mapping from name to the meta object. An example shown in this main.cpp:
#include <QCoreApplication>
#include <QtCore>
#include "myqobject.h"
// a global map for mapping strings to QMetaObjects,
// you need header file like this if you want to access it from other .cpp files:
//
// #include <QHash>
// #include <QString>
// class QMetaObject; // forward declaration, enough when only pointer is needed
// extern QHash<QString, const QMetaObject*> metaObjs;
//
QHash<QString, const QMetaObject*> metaObjs;
// optional: create a macro to avoid typing class name twice,
// #c surrounds macro argument with double quotes converting it to string
#define METAOBJS_INSERT(c) (metaObjs.insert(#c, &c::staticMetaObject))
int main()
{
METAOBJS_INSERT(MyQObject);
const QMetaObject *meta = metaObjs["MyQObject"];
qDebug() << "Class name from staticMetaObject: " << meta->className();
QObject *o = meta->newInstance(); // add constructor arguments as needed
MyQObject *mo = qobject_cast<MyQObject*>(o);
if (mo) qDebug() << "Class name from object instance: " << mo->metaObject()->className();
else qDebug() << "Instance creation failed or created wrong class!";
return 0;
}
If you do not want to use QObject, then you need to come up with some similar (probably lighter-weight and without separate compiler step) mechanism of your own.
I had the same problem.
The solution is in two steps:
call qRegisterMetaType() with a pointer type:
qRegisterMetaType<MyClass*>(). this will give you a valid
QMetaObject with call of QMetaType::metaObjectForType(id);
make your constructor Q_INVOKABLE. this will enable a valid call to
QMetaObject::newInstance
And also be sure that your class is derived from QObject and have a Q_OBJECT macro in it.
class A : public QObject
{
Q_OBJECT
public:
A(const A&) {}; // dummy copy contructor that do nothing to disable error message
Q_INVOKABLE A(int test_value = 99999) : TestValue(test_value) {};
int TestValue;
};
Q_DECLARE_METATYPE(A);
int main(int argc, char *argv[])
{
qRegisterMetaType<A>(); //you do not need this
qRegisterMetaType<A*>();//the real registration
int type_id_for_A = QMetaType::type("A"); // valid type id (in my case = 403)
const QMetaObject *meta_object_for_A = QMetaType::metaObjectForType(type_id_for_A); // returns NULL
int type_id_for_A_ptr = QMetaType::type("A*"); // valid type id (in my case = 404)
const QMetaObject *meta_object_for_A_tr = QMetaType::metaObjectForType(type_id_for_A_ptr); // returns NOT NULL
A* A_obj= dynamic_cast<A*>(meta_object_for_A_tr->newInstance(Q_ARG(int, 12345)));
int test_value = A_obj->TestValue; // returns 12345, not 99999
}

Pointers to stack

I am sorry that I cannot support my question with some code (I didnt understand how to structure it so it would be accepted here), but I try anyway.
If I understand correctly, a struct that references a struct of same type would need to do this with contained pointer for reference. Can this pointer reference to allocated space on the stack (instead of the heap) without creating segmentation fault? -
how should this be declared?
Yes, you can use pointers to variables on the stack, but only when the method that provides that stack frame has not returned. For example this will work:
typedef struct
{
int a;
float b;
} s;
void printStruct(const s *s)
{
printf("a=%d, b=%f\n", s->a, s->b);
}
void test()
{
s s;
s.a = 12;
s.b = 34.5f;
printStruct(&s);
}
This will cause an error however, as the stack frame would have disappeared:
s *bad()
{
s s;
s.a = 12;
s.b = 34.5f;
return &s;
}
EDIT: Well I say it will cause an error, but while calling that code with:
int main()
{
test();
s *s = bad();
printStruct(s);
return 0;
}
I get a warning during compilation:
s.c:27:5: warning: function returns address of local variable [enabled by default]
and the program appears to work fine:
$ ./s
a=12, b=34.500000
a=12, b=34.500000
But it is, in fact, broken.
You didn't say what language you are working in, so assuming C for now from the wording of your question... the following code is perfectly valid:
typedef struct str_t_tag {
int foo;
int bar;
struct str_t_tag *pNext;
} str_t;
str_t str1;
str_t str2;
str1.pNext = &str2;
In this example both str1 and str2 are on the stack, but this would also work if either or both were on the heap. The only thing you need to be careful of is that stack variables will be zapped when they go out of scope, so if you had dynamically allocated str1 and passed it back out of a function, you would not want str1->pNext to point to something that was on the stack within that function.
In other words, DON'T DO THIS:
typedef struct str_t_tag {
int foo;
int bar;
struct str_t_tag *pNext;
} str_t;
str_t *func(void)
{
str_t *pStr1 = malloc(sizeof(*pStr1));
str_t str2;
pStr1->pNext = &str2;
return pStr1; /* NO!! pStr1->pNext will point to invalid memory after this */
}
Not sure if this is specifically a C/C++ question, but I'll give C/C++ code as example in anyway.
The only way you can declare it: (with minor variations)
typedef struct abc
{
struct abc *other;
} abc;
other can point to an object on the stack as follows:
abc a, b; // stack objects
b.other = &a;
This is not a question about scope, so I'll skip commenting on possible issues with doing the above.
If, however, you want to assign it to a dynamically created object, there's no way this object can be on the stack.
abc b;
b.other = malloc(sizeof(abc)); // on the heap

Pointers in structure

I'm trying to use a file pointer that I have declared in a structure of linked list, but I keep getting it as a NULL value.
I have the following structure:
struct _hash_table
{
char found;
struct _hash_chain *hash_chain;
}
struct _hash_chain
{
uint64_t value;
FILE *fout;
struct _hash_chain *next;
}
and
struct _hash_table hash_table[TABLE_SIZE];
I keep getting hash_table[i]->hash_chain->fout = NULL and it's pointer address is nil.
Do I need to dynamically allocate memory for the pointer?
struct _hash_table hash_table[TABLE_SIZE]; - This will not allocate memory for struct _hash_chain because hash_chain is pointer variable in _hash_table.
...
struct _hash_table hash_table[TABLE_SIZE];
for (i = 0; i < TABLE_SIZE; i++);
{
hash_table[i].hash_chain = (struct _hash_chain *)malloc(sizeof(struct _hash_chain));
memset(hash_table[i].hash_chain, 0, sizeof(struct _hash_chain));
}
//Then do file open for TABLE_SIZE times
//hash_table[0].hash_chain->fout = fopen("file.txt", "w");
...
Accssing h_table[i].hash_chain without dynamic memory allocation will leads to crash(an undefined behaviour). I hope you will take care of next pointer.

Resources