lundi 27 avril 2020

Possible create an array of different structures in C++

I have some struct like this:

struct A { ... };
struct B { ... };

And I have a template like this:

template<typename struct_arg>
class X { ... }

Now I wanna create an array of arguments as struct like this:

args [2] { A, B };

for (args) {
    X<args[i]> x;
}

Can I possible to create an array like this!?

How to Define a template Class in a .h File and Implement it in a .cpp File

I was working on explicit class template instantiation and my goal is to separate .h functions declarations inside the class and implementation of those functions inside .cpp file.

I have a sample program here:

file: stack_example.h 

#pragma once
#include <iostream>
#include <random>

template<typename T>
class stack_example
{
    T m_Buffer[10];
    int m_Top;
public:
    stack_example() {
        m_Buffer[10] = { 0 };
        m_Top = -1;
    }
//  ~stack_example();
    void push(const T& elem);
    void pop();
    const T& Top();
    bool IsEmpty();
    void display();

};
file: stack_example.cpp 

#include "stack_example.h"

template<typename T>
void stack_example<T>::push(const T& elem){
    m_Buffer[++m_Top] = elem;
}

template<typename T>
const T& stack_example<T>::Top() {
    return m_Buffer[m_Top];
}

template<typename T>
bool stack_example<T>::IsEmpty(){
    return m_Top == -1;
}

template<typename T>
void stack_example<T>::pop() {
    std::cout << "Deleted element is: " << m_Buffer[m_Top] << std::endl;
    m_Top--;
}

template<typename T>
void stack_example<T>::display() {
    for (int i = 0; i <= m_Top;i++) {
        std::cout << m_Buffer[i] << std::endl;
    }
}

#include "stack_example.h"

template<typename T>
void stack_example<T>::push(const T& elem){
    m_Buffer[++m_Top] = elem;
}

template<typename T>
const T& stack_example<T>::Top() {
    return m_Buffer[m_Top];
}

template<typename T>
bool stack_example<T>::IsEmpty(){
    return m_Top == -1;
}

template<typename T>
void stack_example<T>::pop() {
    std::cout << "Deleted element is: " << m_Buffer[m_Top] << std::endl;
    m_Top--;
}

template<typename T>
void stack_example<T>::display() {
    for (int i = 0; i <= m_Top;i++) {
        std::cout << m_Buffer[i] << std::endl;
    }
}

#include "stack_example.h"

template<typename T>
void stack_example<T>::push(const T& elem){
    m_Buffer[++m_Top] = elem;
}

template<typename T>
const T& stack_example<T>::Top() {
    return m_Buffer[m_Top];
}

template<typename T>
bool stack_example<T>::IsEmpty(){
    return m_Top == -1;
}

template<typename T>
void stack_example<T>::pop() {
    std::cout << "Deleted element is: " << m_Buffer[m_Top] << std::endl;
    m_Top--;
}

template<typename T>
void stack_example<T>::display() {
    for (int i = 0; i <= m_Top;i++) {
        std::cout << m_Buffer[i] << std::endl;
    }
}
file: main.cpp

#include "stack_example.h"
#include "stack_example.cpp"

int main() {

    std::random_device dev;
    std::default_random_engine engine(dev());
    std::uniform_int_distribution<>dist(10,20);
    stack_example<int> s;
    for (int i = 0; i < 5;i++) {
        s.push(dist(engine));
    }

    s.display();

    return 0;
}

here in main.cpp if i include stack_example.cpp then it compiles and executes but if its not included then i get error like this

Error   LNK2019 unresolved external symbol "public: void __thiscall stack_example<int>::push(int const &)" (?push@?$stack_example@H@@QAEXABH@Z) referenced in function _main    class_template      

I know this is related to class template instantiation, but i dont have a clear understanding and i read in some resources https://www.codeproject.com/Articles/48575/How-to-Define-a-Template-Class-in-a-h-File-and-Imp regarding this, Only i got is work around but not about class template instantiation. PLease can anyone let me know how to get a solution to this?

How to create a function that outputs the largest number using conditions in c++

/*Description: Write a function called getMax that takes three parameters of type int, and returns the biggest of the three parameters which is of type int. */

#include <iostream>
using namespace std;

// Declare the function getMax and put in three variables.


int getMax(int number, int number2, int number3){
    if( number >= number2 && number >= number3){
        cout << number;
        if(number2 >= number && number2 >= number3)
            cout << number2 ;

    }
    else {
        cout << number3;
    }
    return number, number2, number3;
}

// we now use the function to check for largest values below:
int main(){

    cout << getMax(-13, -22, -3) << endl; //Prints -3
    cout << getMax(9, 8, 9) << endl; //prints 9
    cout << getMax(-5, 4, -7) << endl; //prints 4
    cout << getMax(15, 15, 15) << endl; //prints 15
    return 0;

}

Can't figure out linker error in VS2019 for friend in templated class

Please note - StackOverflow found a dozen similar examples to this one. I went through every one and still can't get my code to compile. This may be similar to another question, but if you say it is - please make sure that the techniques shown in the example allow getting this code to compile. Thanks in advance.

I'm playing around with some basic code trying to get better as a student of C++. I'm sure this is a simple error/mistake, but I can't figure it out:

#include <iostream>
#include <string>

// General templated class
template <typename T>
class AddElements {
private:
    T lhs;
    T rhs;
public:
    AddElements(T lhs_init=T(), T rhs_init=T()): lhs{lhs_init}, rhs{rhs_init} { }
    T add() { return lhs + rhs; }

    friend std::istream& operator>>(std::istream&, const AddElements&);
};

template <typename T>
std::istream& operator>>(std::istream& istr, const AddElements<T>& ae) {
    istr >> ae.lhs;
    istr >> ae.rhs;
    return istr;
}

int main() {
    std::size_t lines;
    std::string line_types;
    AddElements<int> mycol_ints;

    std::cin >> lines;
    std::cin >> mycol_ints;

    return 0;
}

I'm using Visual Studio 2019's C++ compiler:

$env:cl = "/EHsc /Wall /external:anglebrackets /external:W3 /external:templates- /experimental:external /RTCsu /sdl /analyze /std:c++17"

cl classtemplates.cpp
(...)
/out:classtemplates.exe
classtemplates.obj
classtemplates.obj : error LNK2019: unresolved external symbol "class std::basic_istream<char,struct std::char_traits<char> > & __cdecl operator>>(class std::basic_istream<char,struct std::char_traits<char> > &,class AddElements<int> const &)" (??5@YAAAV?$basic_istream@DU?$char_traits@D@std@@@std@@AAV01@ABV?$AddElements@H@@@Z) referenced in function _main
classtemplates.exe : fatal error LNK1120: 1 unresolved externals

Pointers to the fine manual welcome. I've spent a while Googling around and looking at examples on cppreference.com but for now I'm stumped.

Linker error inheriting constructor from template class c++

Disclaimer: I use the name Vector because that's the name of the class in my project, more in the physics/math sense, it is not the same as std::vector, the class for dynamically sized arrays

Summary

In my project, I have a class Vector inherited by class Vector3D. Vector is templated with an int representing it's rank/size. Unfortunately, I am getting an error during compilation and linking (I have put the error through demangling):

Error LNK2019
unresolved external symbol "public: __cdecl Vector<3>::Vector<3>(double * const)" (public: __cdecl Vector<3>::Vector<3>(double * __ptr64 const) __ptr64 referenced in function "public: __cdecl Vector3D::Vector3D(double * const)" (public: __cdecl Vector3D::Vector3D(double * __ptr64 const) __ptr64
C:\GitRepositories\3dModeler\3dModeler\out\build\x64-Debug\3dModeler
C:\GitRepositories\3dModeler\3dModeler\out\build\x64-Debug\vectors.lib(Vector3D.cpp.obj)

As far as I can tell, it's unable to find or link the inherited constructor from Vector<3>, but I could be wrong.

My Code

Class Vector is declared in file Vector.hpp:

/*
    A generic Vector class
*/
#pragma once //aware of the debate around include guards. This is simpler for now, I think
#include <string>
template <int Rank>
class Vector {
public:
    Vector() = default;
    Vector(double vals[Rank]);                      // Constructs the vector with given values
    double dot(Vector<Rank> v);
    Vector<Rank> add(Vector<Rank> v);
    /* 
    Some other stuff...
    */
    //public member variables
    double values[Rank];
};

It is implemented in file Vector.cpp, partially pasted:

#include "Vector.hpp"

template <int Rank>
Vector<Rank>::Vector(double vals[Rank]):values(vals) {}

Class Vector3D is declared in file Vector3D.hpp:

#pragma once
#include <string>
#include "Vector.hpp"
class Vector3D: public Vector<3> {
public:
    Vector3D(Vector<3>); // NOT explicit, so can swap between them 
    Vector3D(double vals[3]);
    Vector3D cross(Vector3D crossWith); // cross product
};

Relevant parts of the implementation in Vector3D.cpp:

#include "Vector3D.hpp"
#include "Vector.hpp"
#include <cmath>
/*
    Constructs a new 3D Vector out of an array in the format {x, y, z}
*/
Vector3D::Vector3D(double vals[3]) : Vector<3>(vals) {}

/*
    Converts a rank 3 vector into a 3-dimensional vector, assuming dimenson 0 is X, 1 is y, and 2 is z
*/
Vector3D::Vector3D(Vector<3> v) : Vector3D( v.values ) {}

Build Context

I am using Visual Studio 2019. I have opted to use CMake. I am on Windows 10 x64. The file system looks something like:

lib/
 - CMakeLists.txt
 - Solid.cpp
 - Solid.hpp
 - vectors/
    - CMakeLists.txt
    - Vector.hpp
    - Vector.cpp
    - Vector3D.hpp
    - Vector3D.cpp

lib/CMakeLists.txt:

add_library (lib STATIC "Solid.cpp")
target_include_directories (lib PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})

add_subdirectory("vectors")
target_link_libraries(lib LINK_PUBLIC vectors)

Library target lib later gets linked into my test executable. File lib/vectors/CMakeLists.txt:

add_library(vectors STATIC "Vector3D.cpp" "Vector.cpp" "Vector3D.hpp" "Vector.hpp" "vectors.hpp")
target_include_directories (vectors PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})

Thanks

This is a very long post. As I'm writing this I'm trying to find something to cut without losing necessary information. Thanks a lot to anybody who even finishes reading this post, let alone tries to help.

Use output of a python function in qt

I have a python file (function.py). This function has an output (integer). In my QT Widget, I have a pushButton and an empty QLineEdit. What I want to do is the following: Once I click on the button, function.py runs and its output must be written in the QLineEdit. How can I link between my QT project and my python file?

How to properly add qrc (resource) folder on CMAKE for catkin workspace

I have been trying to include in my CMAKE file a resource folder. Contrarily to a typical folder, this is a catkin_ws, and that is why I am having a bit of difficulties: Project compiles but when I launch the GUI, there are no icons, which means that catkin does not see correctly the resource folder:

Belwo is my CMAKE file:

cmake_minimum_required(VERSION 2.8.3)
project(project)
add_compile_options(-std=c++11)
find_package(catkin REQUIRED COMPONENTS 
  roscpp
  pcl_conversions
  pcl_ros
  std_msgs
  lidar_boat_detection
  rviz
)

###
### QT
###
set(CMAKE_AUTOMOC ON) 
set(CMAKE_AUTORCC ON)  

set(CMAKE_INCLUDE_CURRENT_DIR ON)

find_package(Qt5Widgets REQUIRED)
find_package(Qt5PrintSupport)
#find all the qt UI stuff
file(GLOB UI
    "src/filterPCDInterface/*.ui"
)

#make them into headers
qt5_wrap_ui (MB_UI_HDRS  ${UI})

# Generate resources 
qt5_add_resources(RESOURCES_RCC ${RESOURCE})

include_directories(include ${catkin_INCLUDE_DIRS})

file(GLOB SRCS
    "src/filterPCDInterface/*.h"
    "src/filterPCDInterface/*.cpp"
    "src/filterPCDInterface/*.hpp"
)

file(GLOB QT_SRCS
    "src/filterPCDInterface/*.h"
    "src/filterPCDInterface/*.cpp"
    "src/filterPCDInterface/*.hpp"
)

## Declare a catkin package
catkin_package()

add_executable(filterpcdinterface ${MB_UI_HDRS} ${QT_SRCS} ${SRCS} ${RESOURCE})
target_link_libraries(filterpcdinterface  Qt5::Widgets  Qt5::PrintSupport Qt5::Core ${catkin_LIBRARIES} ${PCL_LIBRARIES} )

My res.qrc is the one below:

<RCC>
    <qresource prefix="/icons">
        <file>down-arrow.png</file>
        <file>leftArrow.png</file>
        <file>rightArrow.png</file>
        <file>uoArrow.png</file>
    </qresource>
</RCC>

Also below is a print screen of my resource file:

rcc

Below also how my node folder. In order to get to the icons the path is src/folderA/qrc/icons.png

rcc_qrc

What I have done so far:

1) I found a very useful source that really helped to set almost all the project and the related catkin_ws. I also followed what was said in the post but still catkin_make does not see the resource file. It compiles but when I launch the GUI, there are no icons.

2) Also I came across this additional source which was useful but still not able to solve the problem I have.

Please point to the right direction to solve this issue.