Cannot convert objects to pointers C++ - pointers

I've stayed up all night trying to figure this out (it's now 7am where I'm at...).
I'm having trouble setting the address of an instantiated object to a pointer. Here's the main function:
#include "position_vector.h"
int main(){
PositionVector res = PositionVector(10);
PositionVector * ptr;
ptr = &res; // <--- WHERE IT BREAKS
}
A stripped down version of the h file "position_vector.h":
#include<iostream>
typedef uint32_t word_t;
class PositionVector {
public:
word_t * vec;
/*some other member variables */
PositionVector();
PositionVector(size_t len);
PositionVector & operator & ();
PositionVector & operator !();
~PositionVector();
/*some other member functions*/
void resize(size_t len);
};
I have another cpp file that defines all the methods in the class.
This is part of some larger set of code but here's the compile that fails:
g++-4.9 -std=c++11 -Werror -Wall -Wextra -g -Isrc -ggdb -c -o bin/main.o src/main.cpp
It fails with the error:
g++-4.9 -std=c++11 -Werror -Wall -Wextra -g -Isrc -ggdb -c -o bin/main.o src/main.cpp
src/main.cpp: In function ‘int main()’:
src/main.cpp:27:9: error: cannot convert ‘PositionVector’ to ‘PositionVector*’ in assignment
ptr = &res;
^
I must be missing something super basic but I've just pulled an all nighter and I have to run to work... so I cant really think full well any more.

You've overloaded operator& in your class:
class PositionVector {
// ...
PositionVector & operator & ();
};
When you than try to take the address, the compiler calls your overloaded member function which returns a PositionVector&. This cannot be assigned to a PositionVector* and thus you get the error.

Related

Embeddable Common Lisp (ECL): load shared library with extension functions

Is it possible to load a shared library in ECL, import some C functions which receive and return cl_object (as if they were defined with ecl_def_c_function()) and invoke them in REPL (without compiling a *.lisp file)?
For example:
// file 'extensions.c' compiled to 'extensions.so'
cl_object
do_something
(cl_object arg)
{
cl_object
result = ...;
return result;
}
; in ECL REPL
(uffi:load-foreign-library #p".../extensions.so")
... ; importing stuff
(format t "got: ~a~%" (do-something "text"))
As I found there's no way of telling ECL (via UFFI) that C functions deal with cl_object, not a regular pointer (void*).
Looks like you can't do it as easy as in Python.
The only solution I found so far:
extlib.c
#include <stdio.h>
#include <ecl/ecl.h>
static
cl_object
make_pair
(cl_object arg)
{
return cl_cons(arg, arg);
}
void
init_extlib
(void)
{
ecl_def_c_function(
ecl_read_from_cstring("make-pair"),
make_pair,
1
);
}
Compile it:
clang `ecl-config --cflags` extlib.c -shared -fPIC -o extlib.so `ecl-config --libs`
load-extlib.lisp
(uffi:load-foreign-library "~/extlib.so")
(uffi:def-function ("init_extlib" init-extlib)
()
:returning :void)
(init-extlib)
Compile it:
ecl -compile load-extlib.lisp -o load-extlib.fas
Load & test it:
ecl -load load-extlib.fas
> (make-pair "blah")
("blah" . "blah")

How to get Rcpp and BH (Boost headers) working with regex_replace for Windows build

I'm using the excellent Rcpp project to implement some faster text processing in R, but cannot get the package to build correctly under Windows. (It builds fine under OS X and Linux.) I am using Rcpp, and the BH header packages. I can get the example at http://gallery.rcpp.org/articles/boost-regular-expressions/ and I can get the code below to build on every platform except Windows.
To isolate my problem I removed it from my larger package, and put it into a simple package so that it can be installed using devtools::install_github("kbenoit/boostTest").
The files are:
Makevars.win:
PKG_LIBS = -lboost_regex
src/clean.cpp:
#include <Rcpp.h>
#include <string>
#include <boost/regex.hpp>
// [[Rcpp::depends(BH)]]
const boost::regex re_digits("[[:digit:]]");
const boost::regex re_punct("[[:punct:]]");
const std::string space0("");
std::string removeDigits(const std::string& s) {
return boost::regex_replace(s, re_digits, space0, boost::match_default | boost::format_sed);
}
std::string removePunct(const std::string& s) {
return boost::regex_replace(s, re_punct, space0, boost::match_default | boost::format_sed);
}
// [[Rcpp::export]]
Rcpp::DataFrame cleanCpp(std::vector<std::string> str) {
int n = str.size();
for (int i=0; i<n; i++) {
str[i] = removeDigits(str[i]);
str[i] = removePunct(str[i]);
}
return Rcpp::DataFrame::create (Rcpp::Named("text") = str);
}
and cleanC.R is exported as:
cleanC <- function(x) as.character(cleanCpp(x)[, 1])
(I did this because I am so new to Rcpp that I could not figure out how to return a CharacterVector, but could get the Rcpp::DataFrame return type working by following the boost-regular-expressions example linked above.
In my DESCRIPTION file I have:
LinkingTo: Rcpp,BH
The problem is that when I build the package using devtools::build_win(), it fails, even though it builds fine on Linux and OS X. The output can be seen here:
* installing *source* package 'boostTest' ...
** libs
*** arch - i386
g++ -I"D:/RCompile/recent/R-3.1.3/include" -I"d:/RCompile/CRANpkg/lib/3.1/Rcpp/include" -I"d:/RCompile/CRANpkg/lib/3.1/RcppArmadillo/include" -I"d:/RCompile/CRANpkg/lib/3.1/BH/include" -I"d:/RCompile/r-compiling/local/local320/include" -O3 -Wall -mtune=core2 -c RcppExports.cpp -o RcppExports.o
g++ -I"D:/RCompile/recent/R-3.1.3/include" -I"d:/RCompile/CRANpkg/lib/3.1/Rcpp/include" -I"d:/RCompile/CRANpkg/lib/3.1/RcppArmadillo/include" -I"d:/RCompile/CRANpkg/lib/3.1/BH/include" -I"d:/RCompile/r-compiling/local/local320/include" -O3 -Wall -mtune=core2 -c clean.cpp -o clean.o
g++ -shared -s -static-libgcc -o boostTest.dll tmp.def RcppExports.o clean.o -lboost_regex -Ld:/RCompile/r-compiling/local/local320/lib/i386 -Ld:/RCompile/r-compiling/local/local320/lib -LD:/RCompile/recent/R-3.1.3/bin/i386 -lR
d:/compiler/gcc-4.6.3/bin/../lib/gcc/i686-w64-mingw32/4.6.3/../../../../i686-w64-mingw32/bin/ld.exe: cannot find -lboost_regex
collect2: ld returned 1 exit status
no DLL was created
ERROR: compilation failed for package 'boostTest'
* removing 'd:/RCompile/CRANguest/R-release/lib/boostTest'
Any help appreciated!

Opencv2 cvtColor() does not work

I am using OpenCV2 on Ubuntu 12.04. I can successfully run image read-display codes.
However I am not able to run codes with inbuilt functions eg. cvtColor()
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <stdio.h>
int main(int argc, char *argv[])
{
cv::Mat image = cv::imread("img.jpg");
if( image.data == NULL )
{
printf( "file cannot be loaded\n");
return 1;
}
cv::namedWindow("My");
cv::imshow("My", image);
cv::Mat result;
cv::cvtColor(image, result, CV_BGR2Luv);
cv::imwrite("outImg.jpg", result);
cv::waitKey(0);
return 0;
}
I am using Qt-creator for my OpenCV
After compiling with --libs, --cflags I get following compiler error:
make: Entering directory `/home/swaroop/Work/ai-junkies/cuda/uc_davis/opencv2.x/OpenCV2Test'
g++ -g -c -pipe -O2 -Wall -W -D_REENTRANT -DQT_WEBKIT -DQT_NO_DEBUG -DQT_CORE_LIB -DQT_SHARED -I/usr/share/qt4/mkspecs/linux-g++ -I. -I/usr/include/qt4/QtCore -I/usr/include/qt4 -I/usr/include/opencv -I. -o main.o main.cpp
main.cpp: In function 'int main(int, char**)':
main.cpp:22:29: error: 'CV_BGR2Luv' was not declared in this scope
main.cpp:22:39: error: 'cvtColor' was not declared in this scope
Please help me fix this.
cvtColor declared in opencv2/imgproc/imgproc.hpp
keep in mind it's #include not #import
#include <opencv2/imgproc/imgproc.hpp>
Alternatively, if you are testing things and not concerned with overdoing the includes, you can simply have one line:
#include <opencv2/opencv.hpp>
and it will include most opencv2 headers.

Using QApplication with command line arguments

QApplication::QApplication ( int & argc, char ** argv )
Initializes the window system and constructs an application object
with argc command line arguments in argv.
Warning: The data referred to by argc and argv must stay valid for the
entire lifetime of the QApplication object. In addition, argc must be
greater than zero and argv must contain at least one valid character
string.
From this link: http://doc.qt.io/qt-4.8/qapplication.html#QApplication
What can be the arguments to the executable file? Any examples?
I tried specifying something like:
anisha#linux-dopx:~/Desktop/notes/qt> make
g++ -c -m64 -pipe -O2 -Wall -W -D_REENTRANT -DQT_NO_DEBUG -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED -I../../../qtsdk-2010.05/qt/mkspecs/linux-g++-64 -I. -I../../../qtsdk-2010.05/qt/include/QtCore -I../../../qtsdk-2010.05/qt/include/QtGui -I../../../qtsdk-2010.05/qt/include -I. -I. -o widgets.o widgets.cpp
g++ -m64 -Wl,-O1 -Wl,-rpath,/home/anisha/qtsdk-2010.05/qt/lib -o qt widgets.o -L/home/anisha/qtsdk-2010.05/qt/lib -lQtGui -L/home/anisha/qtsdk-2010.05/qt/lib -L/usr/X11R6/lib64 -lQtCore -lpthread
anisha#linux-dopx:~/Desktop/notes/qt> ./qt 2 f g
anisha#linux-dopx:~/Desktop/notes/qt>
Nothing special happened, nor I knew what I was doing or what I was supposed to do.
EDIT 1: The code on which I tried the ./qt -style=windows.
#include <QtGui>
int main (int argc, char *argv[])
{
QApplication app (argc, argv);
QWidget objQWidget;
objQWidget.show ();
objQWidget.resize (320, 240);
objQWidget.setWindowTitle ("Text to be shown on the title bar\n");
// Adding a "child" widget.
QPushButton *objQPushButton = new QPushButton ("Text to be shown on the button", &objQWidget);
objQPushButton->move (100, 100);
objQPushButton->show ();
return app.exec ();
}
The arguments passed in the constructor are later accessible through the static method
QStringList QCoreApplication::arguments(). By this, command line arguments can be handled everywhere in your code.
Continue reading that documentation. The set of flags QApplication acts on is listed there.
Try for example:
./qt -style=windows
The arguments that QApplication doesn't deal with are simply left alone. The ones it does process are removed (which is why that function takes non-const arguments).
The suggestion about using QCoreApplication is only recommended of you have a console application. If you are using a QApplication instead, and want to access command-line arguments from inside a QWidget, you can do it with the global pointer qApp:
Here you can find the documentation from Nokia, or here from qt-project.org . In the documentation browser of Qt Creator I couldn't find it, so it is at best not that easily accessible.
so you can find:
int my_argc = qApp->arguments().count();
QString my_argv_0 = qApp->arguments.at(0);
...
and so on.
I know this question is old, but took me some time to find a way to do it from within my Main Window, so hope this helps someone else.
Thanks, Dissident penguin! This helped me a lot!
Just note that:
QString my_argv_0 = qApp->arguments.at(0);
should be replaced with:
QString my_argv_0 = qApp->arguments().at(0);
(note the additional () after 'arguments')

QT: Store QTextStream in QList

I'm trying to open multiple files simultaneously (random number of files) and store their textstreams in qlist for simple using in other code:
QList<QTextStream> files;
QList<QString> fnames;
fnames.append("file1.txt");
fnames.append("file2.txt");
// ..and so on with random iterations
// collect qtextsrams into qlist
foreach (QString file, fnames) {
QFile f(file);
f.open(QIODevice::ReadOnly);
QTextStream textStream(&f);
files2.append(&textStream);
}
// use qtextstreams in a loop
QList<QTextStream>::iterator i;
for (i = files.begin(); i != files.end(); ++i) {
qDebug() << i->readLine();
}
So i have an error:
/make debug
make -f Makefile.Debug
make[1]: Entering directory `/home/pixx/Workspace/collocs'
g++ -c -pipe -g -Wall -W -D_REENTRANT -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED -I/usr/share/qt4/mkspecs/linux-g++ -I. -I/usr/include/qt4/QtCore -I/usr/include/qt4/QtGui -I/usr/include/qt4 -Idebug -o debug/main.o main.cpp
main.cpp: In function ‘int main(int, char**)’:
main.cpp:128: error: no matching function for call to ‘QList<QTextStream>::append(QTextStream*)’
/usr/include/qt4/QtCore/qlist.h:493: note: candidates are: void QList<T>::append(const T&) [with T = QTextStream]
/usr/include/qt4/QtCore/qlist.h:819: note: void QList<T>::append(const QList<T>&) [with T = QTextStream]
main.cpp:117: warning: unused variable ‘cc’
In file included from /usr/include/qt4/QtCore/QList:1,
from main.cpp:1:
/usr/include/qt4/QtCore/qtextstream.h: In member function ‘void QList<T>::node_copy(QList<T>::Node*, QList<T>::Node*, QList<T>::Node*) [with T = QTextStream]’:
/usr/include/qt4/QtCore/qlist.h:695: instantiated from ‘void QList<T>::detach_helper(int) [with T = QTextStream]’
/usr/include/qt4/QtCore/qlist.h:709: instantiated from ‘void QList<T>::detach_helper() [with T = QTextStream]’
/usr/include/qt4/QtCore/qlist.h:126: instantiated from ‘void QList<T>::detach() [with T = QTextStream]’
/usr/include/qt4/QtCore/qlist.h:254: instantiated from ‘QList<T>::iterator QList<T>::begin() [with T = QTextStream]’
main.cpp:133: instantiated from here
/usr/include/qt4/QtCore/qtextstream.h:258: error: ‘QTextStream::QTextStream(const QTextStream&)’ is private
/usr/include/qt4/QtCore/qlist.h:386: error: within this context
/usr/include/qt4/QtCore/qtextstream.h:258: error: ‘QTextStream::QTextStream(const QTextStream&)’ is private
/usr/include/qt4/QtCore/qlist.h:399: error: within this context
make[1]: Leaving directory `/home/pixx/Workspace/collocs'
make[1]: *** [debug/main.o] Error 1
make: *** [debug] Error 2
What should i fix?
I understand that it's very simple question, but i can't find right query for google :(
The first error, namely "no matching function for call to ‘QList::append(QTextStream*)’" is caused by you using & operator in this line:
files2.append(&textStream);
Your list is supposed to be made of QTextStream objects, not pointers to QTextStream objects.
But the real problem lies deeper. To put an object into a list, an object must have copy constructor. QTextStream doesn't have any, since it's not clear how different copies of a same text stream should work together. I suggest you create a list of pointers to text streams, as in "QList ". Of course, in that case don't forget to handle their destruction, when they are no longer needed:
foreach (QTextStream *cur, files) delete cur;
If you need to pass this list between different parts of your code, make multiple copies of it and such, you may need smart pointers (QSharedPointer), but I can hardly think of a task where you'd need to do it to text streams.
I found a solution, thanks Septagram for idea! QList files2; // file list to merge
QList<QTextStream> files;
QList<QString> fnames;
fnames.append("file1.txt");
fnames.append("file2.txt");
// ..and so on with random iterations
QList<QFile *> files2; // file list to merge
QList<QTextStream *> files3;
foreach (QString file, files) {
files2.append(new QFile(file)); // create file obj
files2.last()->open(QIODevice::ReadOnly); // open file
files3.append(new QTextStream(files2.last())); // create textstream
}
QList< QTextStream * >::iterator i3;
for (i3 = files3.begin(); i3 != files3.end(); ++i3) {
qDebug() << (*i3)->readLine();
}

Resources