lundi 31 mai 2021

Passing an rvalue reference to an overloaded function still results in ambiguity

The code:

#include <iostream>
#include <utility>

void afunc(int)
    {
    std::cout << "\nafunc(int)\n";
    }
    
void afunc(int &&)
    {
    std::cout << "\nafunc(int &&)\n";
    }
    
int main()
  {
  
  int i = 0;
  
  afunc(std::move(i));
  }

The compiler gives me an error saying that the call to afunc is ambiguous.

I am passing an rvalue reference to an int to a function which takes either a value or an rvalue reference for an int. I do not understand why the exact match match is not preferred. It is not as if I am passing something which can be considered an int or an rvalue reference to an int, such as the literal 0, in which case I can understand the ambiguity. The std::move function specifically creates the rvalue reference. Would someone please enlighten me on why the exact match is not preferred and the call is considered ambiguous ?

Baffling variadic templates exercise

I set myself this task to help learn variadic templates. The function add_and_cat() should take first a pair<int,string>, then a variable number of ints or strings or a mixture. As it encounters these recursively, it should subtract each int from pair.first, and concatenate each string onto pair.second. The function pp just prints the pair.

It seems to work in many cases, but in others I get a compile error claiming no matching function (at the bottom) ... even though there seems to be only one perfectly obvious candidate as far as I can tell :/ I've played around and tried to reason it out but ... no luck yet. What am I missing?

-------------------------- Code: ----------------------------

#include <iostream>

void pp(std::pair<int,std::string> printme) {
    std::cout << printme.first << " : " << printme.second << "\n";
}

//base case int
//must be int or std::string for now
void add_and_cat(std::pair<int, std::string>& store, int i) {
    store.first -= i;
    store;
}

//base case string
void add_and_cat(std::pair<int, std::string>& store, std::string s) {
    store.second += s;
    store;
}

//full case for int
template<typename ...Ts>
void add_and_cat(std::pair<int, std::string>& store, int i, Ts... rest) {
    store.first -= i;
    add_and_cat(store, rest...);
}

//full case for string
template<typename ...Ts>
void add_and_cat(std::pair<int, std::string>& store, std::string s, Ts... rest) {
    store.second += s;
    add_and_cat(store, rest...);
}



int main()
{

    std::pair<int, std::string> p{0,"START"};

    //add_and_cat(p, 1, 2, 3, 4); pp(p);                    //fine
    //add_and_cat(p, 3, 4, 5, 6); pp(p);                    //fine
    //add_and_cat(p, "A", "B", "C", "D"); pp(p);            //fine
    //add_and_cat(p, "D", "E", "F", "G"); pp(p);            //fine
    //add_and_cat(p, "A", 1, "B"); pp(p);                   //fine
    //add_and_cat(p, 1, "A", 1, "B"); pp(p);                //compile error
    //add_and_cat(p, 1, 2, "A",3); pp(p);                   //compile error
    //add_and_cat(p, "A", 1, 2, "B"); pp(p);                //fine
    //add_and_cat(p, "A", 1, 2, "B","C"); pp(p);            //compile error
    //add_and_cat(p, 1, 2, "B","C"); pp(p);             //compile error



    return 0;
}

------------------------------ Error: -----------------------------

/mnt/c/Users/Tim/Nextcloud/playground/seqan3/source/hello_world.cpp: In instantiation of ‘std::pair<int, std::__cxx11::basic_string<char> > add_and_cat(std::pair<int, std::__cxx11::basic_string<char> >&, int, Ts ...) [with Ts = {const char*, int, const char*}]’:
/mnt/c/Users/Tim/Nextcloud/playground/seqan3/source/hello_world.cpp:273:45:   required from here
/mnt/c/Users/Tim/Nextcloud/playground/seqan3/source/hello_world.cpp:250:20: error: no matching function for call to ‘add_and_cat(std::pair<int, std::__cxx11::basic_string<char> >&, const char*&, int&, const char*&)’
  250 |  return add_and_cat(store, rest...);
      |         ~~~~~~~~~~~^~~~~~~~~~~~~~~~
/mnt/c/Users/Tim/Nextcloud/playground/seqan3/source/hello_world.cpp:233:29: note: candidate: ‘std::pair<int, std::__cxx11::basic_string<char> > add_and_cat(std::pair<int, std::__cxx11::basic_string<char> >&, int)’
  233 | std::pair<int, std::string> add_and_cat(std::pair<int, std::string>& store, int i) {
      |                             ^~~~~~~~~~~
/mnt/c/Users/Tim/Nextcloud/playground/seqan3/source/hello_world.cpp:233:29: note:   candidate expects 2 arguments, 4 provided
/mnt/c/Users/Tim/Nextcloud/playground/seqan3/source/hello_world.cpp:240:29: note: candidate: ‘std::pair<int, std::__cxx11::basic_string<char> > add_and_cat(std::pair<int, std::__cxx11::basic_string<char> >&, std::string)’
  240 | std::pair<int, std::string> add_and_cat(std::pair<int, std::string>& store, std::string s) {
      |                             ^~~~~~~~~~~
/mnt/c/Users/Tim/Nextcloud/playground/seqan3/source/hello_world.cpp:240:29: note:   candidate expects 2 arguments, 4 provided
/mnt/c/Users/Tim/Nextcloud/playground/seqan3/source/hello_world.cpp:247:29: note: candidate: ‘template<class ... Ts> std::pair<int, std::__cxx11::basic_string<char> > add_and_cat(std::pair<int, std::__cxx11::basic_string<char> >&, int, Ts ...)’
  247 | std::pair<int, std::string> add_and_cat(std::pair<int, std::string>& store, int i, Ts... rest) {
      |                             ^~~~~~~~~~~
/mnt/c/Users/Tim/Nextcloud/playground/seqan3/source/hello_world.cpp:247:29: note:   template argument deduction/substitution failed:
/mnt/c/Users/Tim/Nextcloud/playground/seqan3/source/hello_world.cpp:250:28: note:   cannot convert ‘rest#0’ (type ‘const char*’) to type ‘int’
  250 |  return add_and_cat(store, rest...);
      |                            ^~~~

Thanks so much for any help!

Choosing overload between a type and an rvalue reference of that type

I thought I understood rvalue references but evidently I am missing something when it comes to function overloading. Given the code:

#include <iostream>
#include <utility>

void afunc(int)
    {
    std::cout << "\nafunc(int)\n";
    }
    
void afunc(int &&)
    {
    std::cout << "\nafunc(int &&)\n";
    }
    
int main()
  {
  
  int i = 0;
  
  afunc(std::move(i));
  }

I would have assumed that the second call to afunc would be chosen, but instead I get that the error that the call to afunc is ambiguous. Since std::move(i), as I understand it, creates an rvalue reference to i, an int, I do not understand why the second call to afunc does not match exactly. Can someone please explain what I am understanding that is wrong ?

This is clearly not the same question as Overload resolution between object, rvalue reference, const reference. In the previous question an int is being passed while here an int && is being passed, which should match exactly only one of the function calls.

When I return object from function a copy constructor is called only of its an formal argument unless it is not calling copy constructor why so? [closed]

Code of creating temporary object inside fun

Result:No copy constructor called

Code of passing with parameter copy constructor called at return value why

Why copy con called at return value

Only retuning object

Still copy constructor called why??

dimanche 30 mai 2021

How shared pointers leads to thread safety in multhreading

I understood the concept of shared pointers but not able to understand why this is used as thread safe. While searching, got to know that returning pointers or references is not thread safe, how? Also, how the use of shared pointers make it thread safe. Please elaborate or point me to some documentation or resources where I can read and understand this concept.

C++ Is my code leaning towards becoming spaghetti like? Am I using to many switch statements. Is there something better practice to do? [closed]

I'm attempting to build a "simple" program based on the bus schedule in my area. It displays the 12 available bus stops. Then selecting your departure time and choosing the Ending destination point. What I would like to know before I try to implement the math of the code. Is what' I've written efficient or unnecessary lines of code?

#include <iostream>
using namespace std;

void BusTravelingDistance(){}; //function to do some math from distance in mile/km point a to b
void BusTravelingTime(){}; //function to do some math length of time traveled HH:MM

int main() //Downtown Hilo to Kaumana.
{
    int choice;
    int BusPickUpLocation[12];
    int BusDropOffLocation[11];

    std::cout << "Chose you starting location by Number: " <<endl;
    std::cout << " 1.Prince kuhio plaza, 2.Aupuni center, 3.hilo Airport, 4.Banyan drive,\n 5.Mooheau bus terminal, 6.Waianuenue ave, 7.Arc of hilo, 8.Hilo medical center,\n 9.Ainako ave, 10.Kaumama drive, 11.Genrey subdivision, 12.Kaumama city" <<endl;
    std::cin >> BusPickUpLocation[12];

    switch (BusPickUpLocation[12])
    {
    case 1:

        std::cout << "Pick up at Prince Kuhio Plaze 1. 7:15AM, 2. 10:10AM, 3. 11:30AM, 4. 4:20PM" <<endl;
        std::cout << "What time are is your departure: " <<endl;
        std::cin >> choice;
        switch (choice)
        {
            case 1:
            {
                std::cout << "You bus arrival is at: 7:15AM\n";
                break;
            }
            case 2:
            {
                std::cout << "Your bus arrival is at: 10:10AM\n";
                break;
            }
            case 3:
            {
                std::cout << "Your bus arrival is at: 11:30AM\n";
                break;
            }           
            case 4:
            {
                std::cout << "Your bus arrival is at 4:20pm\n";
                break;
            }
        }    
        break;

    case 2:
        std::cout << "Pick up at Aupuni Center 1. 2:15PM, 2. 4:38PM" <<endl;
        std::cout << "What time are is your departure: " <<endl;
        std::cin >> choice;
        switch (choice)
        {
            case 1:
            { 
                std::cout << "Your bus arrival is at 2:15PM\n";
                break;
            }      
            case 2:
            {
                std::cout << "Your bus arrival is at 4:35PM\n";
                break;
            }
        }
        break;
        
    case 3:
        std::cout << "Pick up at Hilo Airport 7:25\n";
        break;

    case 4:
        std::cout << "Pick up at Banyon Drive 1. 8:30AM, 2. 10:20AM, 3. 11:40AM";
        std::cout << "What time are is your departure: " <<endl;
        std::cin >> choice;
        switch (choice)
        {
        case 1:
            {
                std::cout << "Your bus arrival is at 8:30AM\n";
                break;
            }      
        case 2:
            {
                std::cout << "Your bus arrival is at 10:20AM\n";
                break;
            }               
        case 3:
            {
                std::cout << "Your bus arrival is at 11:40AM\n";
                break;
            }
        }
        break;
    case 5:
        std::cout << "Pick up at Mo Oheau Bus Terminal 1. 7:35AM, 2. 8:35AM,  3. 10:25AM, 4. 11:45AM, 5. 2:20PM, 6. 4:45PM";
        std::cout << "What time are is your departure: " <<endl;
        std::cin >> choice;
        switch (choice)
        {
        case 1:
            {
                std::cout << "Your bus arrival is at 7:35AM\n";
                break;
            }
        case 2:
            {
                std::cout << "Your bus arrival is at 8:35AM\n";
                break;
            }
        case 3:
            {
                std::cout << "Your bus arrival is at 10:25AM\n";
                break;
            }
        case 4:
            {
                std::cout << "Your bus arrival is at 11:45AM\n";
                break;
            }
        case 5:
            {
                std::cout << "Your bus arrival is at 2:20PM\n";
                break;
            }
        case 6:
            {
                std::cout << "Your bus arrival is at 4:45PM\n";
                break;
            }
        }
        break;

    case 6:
        std::cout << "Pick up at Waianuenue Ave(post office,library,hilo high) 1. 8:40AM, 2. 10:30AM, 3. 11:55AM, 4. 2:25PM, 5. 4:50PM";
        std::cout << "What time are is your departure: " <<endl;
        std::cin >> choice;
        switch(choice)
        {
            case 1:
            {
                std::cout << "Your bus arrival is at 8:40AM\n";
                break;
            }
            case 2:
            {
                std::cout << "Your bus arrival is at 10:30AM\n";
                break;
            }
            case 3:
            {
                std::cout << "Your bus arrival is at 11:55AM\n";
                break;
            }
            case 4:
            {
                std::cout << "Your bus arrival is at 2:25PM\n";
                break;
            }
            case 5:
            {
                std::cout << "Your bus arrival is at 4:50PM\n";
                break;
            }
        }
        break;
    
    case 7:
        std::cout << "Pick up at Ark of Hilo 7:44AM, 8:44AM, 10:34AM, 11:59AM, 2:29PM";
        break;

    case 8:
        std::cout << "Pick up at Hilo Medical Center 7:45AM, 8:45AM, 10:353AM, 12:00PM, 2:30PM, 4:55PM";   
        break; 

    case 9:
        std::cout << "Pick up at Ainako Ave 7:50AM, 8:50AM, 10:40AM, 12:05PM, 2:35PM, 5:00PM";   
        break; 

    case 10:
        std::cout << "Pick up at Kaumana Drive 2:40PM";   
        break; 

    case 11:
        std::cout << "Pick up at Gentry Subdivision 5:10PM";  
        break; 
    default:
        std::cout << "Final Stop Kaumama City 9:00AM, 12:15PM, 2:50PM, 5:20PM\n Heading back to Hilo from Kaumana City?\n I haven't gotten that far into the program... ";
    }


    std::cout << "What is the drop off location: " <<endl;
    std::cout << "1.Aupuni center, 2.hilo Airport, 3.Banyan drive,\n 4.Mooheau bus terminal, 5.Waianuenue ave, 6.Arc of hilo, 7.Hilo medical center,\n 8.Ainako ave, 9.Kaumama drive, 10.Genrey subdivision, 11.Kaumama city" <<endl;
    std::cin >> BusDropOffLocation[11];

}

pure virtual method called, terminate called without an active exception

I'm trying to finish my project but when I'm trying to test my program I keep facing the same error I mentioned above. The program was running perfectly until I started testing it and I just cant figure out what causes the error.

Basically I have City class:

#pragma once

#include <ostream>

class Japan;
class Modern;
class Other;

class City{
    protected:
        int _pont;
    public:
        virtual void touristModify(Japan* t)  = 0;
        virtual void touristModify(Modern* t) = 0;
        virtual void touristModify(Other* t)  = 0;
        virtual City* instanceChange() const = 0;
        virtual std::string type() const = 0;
        void setPont(int p);
        int pont() const;
        virtual ~City(){}
        friend std::ostream &operator<<(std::ostream &os,const City &City);
};

class BadCondition: public City{
    public:
        static BadCondition* instance();
        City* instanceChange() const override;
        std::string type() const override;
        void touristModify(Japan* t) override;
        void touristModify(Modern* t) override { }
        void touristModify(Other* t) override { }
        BadCondition(){}
    private:
        static BadCondition* _instance;
};

class Avarage: public City{
    public:
        static Avarage* instance();
        City* instanceChange() const override;
        std::string type() const override;
        void touristModify(Japan* t) override { }
        void touristModify(Modern* t) override;
        void touristModify(Other* t) override;
        Avarage(){}
    private:
        static Avarage* _instance;
};

class GoodCondition: public City{
    public:
        static GoodCondition* instance();
        City* instanceChange() const override;
        std::string type() const override;
        void touristModify(Japan* t) override;
        void touristModify(Modern* t) override;
        void touristModify(Other* t) override { }
        GoodCondition(){}
    private:
        static GoodCondition* _instance;
};
 

a cpp file:

#include "tourist.h"

using namespace std;


int City::pont() const{
    return _pont;
}

void City::setPont(int p){
    if(p < 1){
        _pont = 1;
    }else if(p > 100){
        _pont = 100;
    }else{
        _pont = p;
    }
}

std::ostream &operator<<(std::ostream &os,const City &city)
{
    os << "This city has  "<< city.pont() << " and condition is :" << city.type() << endl;
    return os;
}

BadCondition* BadCondition::_instance = nullptr;

BadCondition* BadCondition::instance(){
    if(_instance == nullptr){
        _instance = new BadCondition();
    }
    return _instance;
}

void BadCondition::touristModify(Japan* t){
    t->setDb(0);
}

City* BadCondition::instanceChange() const{
    if(_pont > 33){
        return Avarage::instance();
    }else if(_pont > 67){
        return GoodCondition::instance();
    }
    return BadCondition::instance();
}

std::string BadCondition::type() const{
    return " BadCondition.";
}

Avarage* Avarage::_instance = nullptr;
Avarage* Avarage::instance(){
    if(_instance == nullptr){
        _instance = new Avarage();
    }
    return _instance;
}

void Avarage::touristModify(Modern* t){
    t->setDb(t->db() * 1.1);
}

void Avarage::touristModify(Other* t){
    t->setDb(t->db() * 1.1);
}

City* Avarage::instanceChange() const{
    if(_pont < 34){
        return BadCondition::instance();
    }else if(_pont > 67){
        return GoodCondition::instance();
    }
    return Avarage::instance();
}

std::string Avarage::type() const{
    return " Avarage.";
}
GoodCondition* GoodCondition::_instance = nullptr;
GoodCondition* GoodCondition::instance(){
    if(_instance == nullptr){
        _instance = new GoodCondition();
    }
    return _instance;
}

void GoodCondition::touristModify(Japan* t) {
    t->setDb(t->db() * 1.2);
}

void GoodCondition::touristModify(Modern* t){
    t->setDb(t->db() * 1.3);
}

City* GoodCondition::instanceChange() const{
    if(_pont < 34){
        return BadCondition::instance();
    }else if(_pont < 68){
        return Avarage::instance();
    }
    return GoodCondition::instance();
}


std::string GoodCondition::type() const{
    return " in a good condition.";
}

and my main file:

#include "tourist.h"
#include "City.h"
#include <fstream>
#include <vector>


using namespace std;

void create(const string &filename, vector<Tourist*> &tourists, City* &city,int *numberOfYears){
    ifstream f(filename);
    if(f.fail()){
        exit(1);
    }

    int startingPoint = 0;
    f >> startingPoint;
    if(startingPoint < 34){
        city = BadCondition::instance();
    }else if(startingPoint < 68){
        city = Avarage::instance();
    }else {
        city = GoodCondition::instance();
    }
    tourists.empty();
    cout << "City Starting Condition:" << city->type() << endl;
    city->setPont(startingPoint);
    f >> *numberOfYears;
    for(int i=0; i<*numberOfYears; i++){
            int b = 0;
            f >> b;
            tourists.push_back(new Japan(b));
            f >> b;
            tourists.push_back(new Modern(b));
            f >> b;
            tourists.push_back(new Other(b));
    }
    cout << endl;
}

void income(int b, City* &city){
    if(b - 10000 > 0){
        cout << "Not Enough money."<< endl;
    }else{
        cout << "Enough money" << endl;
    }
    if(b > 10000){
        b -= 10000;
        city->setPont(city->pont() + ( b / 200));
    }
    cout << endl;
}

void year(vector<Tourist*> &tourists, City* &city,int pastnumberOfYears){
        int bevetel = 0;
        cout << *city << endl;
        for(int i=pastnumberOfYears * 3; i< pastnumberOfYears*3 + 3; i++){
            tourists[i]->TouristModosit(city);
            bevetel+=tourists[i]->db();
            tourists[i]->szennyezes(city);
        }
        income(bevetel,city);
        int pont = city->pont();
        city = City->allapotValtozas();
        city->setPont(pont);
        cout << *city << endl;
}

void tourism(vector<Tourist*> &tourists, City* &city,int numberOfYears){
    for(int i=0; i<numberOfYears; i++){
        year(tourists,city,i);
    }
}

//#define NORMAL_MODE
//#ifdef NORMAL_MODE

 int main()
 {
     int numberOfYears;
     vector<Tourist*> tourists;
     City* city;
     create("input.txt",tourists, city,&numberOfYears);
     tourism(tourists,city,numberOfYears);
     cout << city->pont() << endl;
     cout << city->type() << endl;
    delete city;
    delete &tourists;
    return 0;
 } 

So whenever I start testing I get the pure virtual method error. Sample test:

TEST_CASE("1 proper year "){
    int numberOfYears;
    vector<Tourist*> tourists;
    City* city;

    SECTION("Lepusztul kezdoallapot"){
        BadConditionKENT VEGZI 1 EV UTAN
        create("input2.txt",tourists, city, &numberOfYears);
        CHECK(city->pont() == 20);
        CHECK(city->type() == " BadCondition.");
        CHECK(numberOfYears == 1);
        CHECK(tourists.size() == 3);
        tourism(tourists,city,numberOfYears);
        CHECK(city->pont() == 1);
        CHECK(city->type() == " BadCondition.");
        delete city;
        delete &tourists;
    }
}

I could really use some help abd thank you for your time and answears!

Is it possible to swap std::array in constant time?

From what I understand, swapping a std::vector is a constant time operation because the only pointers are being swapped, but in the case of an std::array the swapping is element-wise. Is it possible to swap the pointers of an std::array?

Apologies if this has been asked to death already. If so kindly point me in the right direction, thanks.

This DSU problem of UVA is giving WA verdict. I don't get why. Can anyone help it?

Here's the problem link. https://onlinejudge.org/index.php?option=onlinejudge&Itemid=8&page=show_problem&category=0&problem=3638&mosmsg=Submission+received+with+ID+26446583

For each of m groups, I made union of all of the students in the group. At last, for each student from 0 to n-1 I counted how many of them has parent equals 0. Printed that as result. In union function, I always made the smaller number the parent so that eventually 0 becomes parent.

And it looks obvious to me. But don't know why this code below is givng WA :(

    #include<bits/stdc++.h>
using namespace std;

#define ll long long
int par[30005];

int find(int u) {
  if (u==par[u]) return u;
  return par[u]=find(par[u]);
}

void unionn(int u,int v) {
  int p=find(u);
  int q=find(v);
  if (q<p) swap(q,p);
  if (p!=q) par[q]=p;
}
  

int main() {
  ios_base::sync_with_stdio(0);

  /*freopen("input.txt","r",stdin);
  freopen("output.txt","w",stdout);*/

  while (1) {
    int n,m; cin>>n>>m;
    if (n==0&&m==0) break;  
    for (int i=0;i<n;i++) par[i]=i;
    while (m--) {
      int k; cin>>k;
      int a[k];
      for (int i=0;i<k;i++) cin>>a[i];
      for (int i=1;i<k;i++) unionn(a[i],a[i-1]);     
    }
    int res=0;
    for (int i=0;i<n;i++) {
      if (par[i]==0) res++;
    }
    cout<<res<<endl;
  }
   

  
  return 0; 
}

 

Parse a .txt containing a custom data structure

I am trying to load the data present inside a .txt inside a structure. The problem is that the data inside the .txt does not respect a standard such as json, but is customized like this:

data1;
data2;
data3;
[
        {
            user_1,
            [
                {
                    a_1,
                    b_1,
                    c_1,
                    d_1
                },
                ..,
                {
                    a_n,
                    b_n,
                    c_n,
                    d_n
                }
            ]
        },
        ...,
        {
            user_n,
            [
                {
                    a_1,
                    b_1,
                    c_1,
                    d_1
                },
                ..,
                {
                    a_n,
                    b_n,
                    c_n,
                    d_n
                }
            ]
        }
];

I can't find a way to write code that can read inside arrays containing various 'users' with their 'a, b, c, d' data.

Unfortunately, I cannot modify the input data in any way, and furthermore, if characters or fields are missing, the type of error and its position must be precisely identified.

Finally, the file can be without any carriage returns and tabs, but in this case the data must still be read.

Could anyone give me an indication where I could figure out how to solve this problem? I have done various searches on the internet but I have not found anyone who tried to read a txt containing data structured in a personalized way.

Pizza house using array and loop [closed]

Description:
Hope you may all like pizza. Mr. Jonathan Has a pizza shop.In his shop there are some knives to cut different length of pizza . You are one of his Employee and he will give you a circumference of a pizza . Now you have to tell that what is the length to cut the pizza in two equal parts.

Input:
The first line conatins T<=100 which indicates the test case you will be given areal and positive number n . n<=1000.

Output:
For each number , print the test case number and then print the result (3 digits after point)

How to output x++ with operator++ in class? [duplicate]

How to output x++ with operator++ in my class CTimeSpan. I create like the following example:

#include <iostream>
using namespace std;
class CTimeSpan {
private:
    unsigned int day; //day
    unsigned int hour;
    unsigned int minute;
    unsigned int second;

public:
    ostream& operator<<(ostream& os,const CTimeSpan& tm)
    {
        os << tm.day << "d"
           << " " << tm.hour << "h"
           << " " << tm.minute << "p"
           << " " << tm.second << "s";
        return os;
    }
    CTimeSpan CTimeSpan::operator++(int s) {
            CTimeSpan temp = *this;
            ++* this;
            return temp;
     }
};
int main()
{
    CTimeSpan tm1{ 1, 2, 3, 4 };
    cout << tm1++; //it's error "<<"
}

*thank you very much. Help me

C++ template,typename and operator<< : error: explicit instantiation of undefined function template 'operator<<'

error is in the title, here is the code :

Universe.hpp:

// Universe Class
// Damien MATTEI

#ifndef UNIVERSE_HPP
#define UNIVERSE_HPP


#include <algorithm> // used by Universe
#include <iostream>

#include <vector>

#include <list>


// Edge3D will include Point3D
#include "Edge3D.hpp"
#include "Vector3D.hpp"
#include "Object.hpp"

#include "debug.hpp"



using namespace std;



template <typename T> class Universe {
        
public:
   
  // data

  // name must be like containerTYPEptrCONTAINER_TYPEC (must end by a char like C or other only for macro reason (!))
  // where TYPE is the element type contained in the container CONTAINER_TYPE
  
  // example1: TYPE=Point3D , CONTAINER_TYPE=vector
  std::vector< Point3D<T> *> containerPoint3DptrvectorC;
  
  // example2: TYPE=Vector3D , CONTAINER_TYPE=vector
  std::vector< Vector3D<T> *> containerVector3DptrvectorC;

  

  
  // deprecated
  // example3: TYPE=Edge3D , CONTAINER_TYPE=list
  list < Point3D<T> *> containerPoint3DptrlistC;

  list < Edge3D<T> *> containerEdge3DptrlistC;

  // for deprecated compatibility in Vision3D.cpp
  // the vertex
  list < Point3D<T> > vertexList;
  
  Universe();

  ~Universe();
  

  // create a Point3D by checking if it already exist in the universe
  template <typename ObjectType, typename... ParamTypes>
  ObjectType & createPoint3DRefvectorC(ParamTypes ...args);

  // create a Vector3D by checking if it already exist in the universe
  template <typename ObjectType, typename... ParamTypes>
  ObjectType & createVector3DRefvectorC(ParamTypes ...args);




  
  // DEPRECATED (for tests)
  Point3D<T> & createPoint3DReference(T x,T y,T z); // create a point by checking if it already exist
  Point3D<T> & createPoint3Dref_BACKUP(T x,T y,T z); // backup because i created macro that builds functions now


  
  // create a Point3D by checking if it already exist in the universe
  template <typename ObjectType, typename... ParamTypes>
  ObjectType & createPoint3DReflistC(ParamTypes ...args);

  // create a Edge3D by checking if it already exist in the universe
  template <typename ObjectType, typename... ParamTypes>
  ObjectType & createEdge3DReflistC(ParamTypes ...args);



  // create an object by checking if it already exist in the universe
  // DEPRECATED
  template <typename ObjectType, typename... ParamTypes>
  ObjectType & createObjectRef(ParamTypes ...args);
  
  Point3D<T> * createPoint3Dptr(T x,T y,T z); // create a point by checking if it already exist

  void createCube(Point3D<T> &,T);

  // for testing
  template <typename myType,typename otherType>
  myType GetMax (myType a, myType b);

  template <typename U> 
  friend std::ostream&  operator<< (ostream &, const Universe<U> &);

  
};

template <typename U>  std::ostream&  operator<< (ostream &, const Universe<U> &); // does not work !!!



#endif /* UNIVERSE_HPP */

Universe.cpp :

// Universe Class
// Damien MATTEI


#include "Universe.hpp"



// implementations

template <typename T> Universe<T>::Universe() {

 
#ifdef DISPLAY_CONSTRUCTOR
  cout << "# Universe constructor # " << this << endl;
#endif
}

template <typename T> Universe<T>::~Universe() {

  typename vector< Point3D<T> *>::iterator it;
  
  for(it = containerPoint3DptrvectorC.begin(); it != containerPoint3DptrvectorC.end(); it++)  {
    cerr << "# Universe destructor # deleting a containerPoint3DptrvectorC"  << endl;
    delete *it;
  }
  
 typename list< Point3D<T> *>::iterator itLst;
  
 for(itLst = containerPoint3DptrlistC.begin(); itLst != containerPoint3DptrlistC.end(); itLst++)  {
   cerr << "# Universe destructor # deleting a containerPoint3DptrlistC"  << endl;
   delete *itLst;
 }
  
#ifdef DISPLAY_CONSTRUCTOR
  cout << "# Universe destructor # "  << this << endl;
#endif

}


 // for testing
template <typename T>
template <typename myType,typename otherType>
myType Universe<T>::GetMax (myType a, myType b) {
  // otherType i= 7; //useless
 return (a>b?a:b);
}




#define CREATE_OBJECT_TEMPLATED(TYPE,TYPE_CONTAINER)                    \
  /* create an object by checking if it already exist in the universe */ \
template <typename T> \
template <typename ObjectType, typename... ParamTypes> \
\
ObjectType & Universe<T>::create##TYPE##Ref##TYPE_CONTAINER##C(ParamTypes ...args) { \
\
  DEBUG(cerr << "Universe<T>::create" #TYPE "Ref" #TYPE_CONTAINER "C<>" << endl;) \
\
  ObjectType & object = *(new ObjectType(std::forward<ParamTypes>(args) ...));\
\
  DEBUG(cerr << "Universe<T>::create" #TYPE "Ref" #TYPE_CONTAINER "C<> : std::find_if ... " << endl;)\
\
  /* i check unicity of the object in Universe i.e to save memory and speed */ \
  /* i do not want to have two mathematically identical 3D objects */ \
  typename TYPE_CONTAINER < ObjectType *>::iterator iterOBJECTptr = \
    std::find_if(container##TYPE##ptr##TYPE_CONTAINER##C.begin(), container##TYPE##ptr##TYPE_CONTAINER##C.end(), \
         /* lambda in C++ */ \
              [&object](ObjectType * object_ptr_lambda_param) { \
                          ObjectType & object_lambda_param = *object_ptr_lambda_param; \
                          DEBUG(cerr << "Universe<T>::create" #TYPE "Ref" #TYPE_CONTAINER "C<> : in Lambda" << endl;) \
                  return  object_lambda_param == object; \
              } \
         ); \
\
  DEBUG(cerr << "Universe<T>::create" #TYPE "Ref" #TYPE_CONTAINER "C<> : bool found ... " << endl;) \
  bool found = (iterOBJECTptr != container##TYPE##ptr##TYPE_CONTAINER##C.end()); \
\
\
  if (found) { \
\
    DEBUG(cerr << "Universe<T>::create" #TYPE "Ref" #TYPE_CONTAINER "C<> : found ... " << endl;) \
    DEBUG(cerr << "Universe<T>::create" #TYPE "Ref" #TYPE_CONTAINER "C<> : *iterOBJECTptr " << *iterOBJECTptr << endl;) \
      DEBUG(cerr << "Universe<T>::create" #TYPE "Ref" #TYPE_CONTAINER "C<> : **iterOBJECTptr " << **iterOBJECTptr << endl << endl;) \
\
    delete &object; \
\
    return **iterOBJECTptr; /* return the pointer OBJECT */ \
    \
  } \
  else { /* we have to add the point to the universe */ \
    DEBUG(cerr << "Universe<T>::create" #TYPE "Ref" #TYPE_CONTAINER "C<> : NOT found ... " << endl;) \
    DEBUG(cerr << "Universe<T>::create" #TYPE "Ref" #TYPE_CONTAINER "C<> : container" #TYPE "ptr"  #TYPE_CONTAINER "C.push_back(&object);" << endl << endl;) \
\
    container##TYPE##ptr##TYPE_CONTAINER##C.push_back(&object); \
\
    return object; \
  } \
\
}

CREATE_OBJECT_TEMPLATED(Point3D,vector)

CREATE_OBJECT_TEMPLATED(Vector3D,vector)








// DEPRECATED
// this create the Template only for Point3D (not a particular instance for float by example)
// example of call : univ.createPoint3DRef<Point3D<float>,float,float,float>(1,0,0);
CREATE_OBJECT_TEMPLATED(Point3D,list)

CREATE_OBJECT_TEMPLATED(Edge3D,list)




// create an object by checking if it already exist in the universe
// warning: works only with Point3D as the container containerPoint3DptrlistC is statically defined
// DEPRECATED i suppose
template <typename T>
template <typename ObjectType, typename... ParamTypes>

ObjectType & Universe<T>::createObjectRef(ParamTypes ...args) {

  DEBUG(cerr << "Universe<T>::createObjectRef" << endl;)

  ObjectType & object = *(new ObjectType(std::forward<ParamTypes>(args) ...));

    //ObjectType & object =  *(new ObjectType());
    
  DEBUG(cerr << "Universe<T>::createObjectRef : std::find_if ... " << endl;)

  // i check unicity of the point in Universe i.e to save memory and speed
  // i do not want to have two mathematically identical 3D points
  typename list< ObjectType *>::iterator iterOBJECTptr =
    std::find_if(containerPoint3DptrlistC.begin(), containerPoint3DptrlistC.end(),
         // lambda in C++
              [&object](ObjectType * object_ptr_lambda_param) {
                          ObjectType & object_lambda_param = *object_ptr_lambda_param;                  
                          DEBUG(cerr << "Universe<T>::createObjectRef : in Lambda" << endl;)
                  return  object_lambda_param == object;
              }
         );

  DEBUG(cerr << "Universe<T>::createObjectRef : bool found ... " << endl;)
  bool found = (iterOBJECTptr != containerPoint3DptrlistC.end());

  
  if (found) {
    
    DEBUG(cerr << "Universe<T>::createObjectRef : found ... " << endl;)
    DEBUG(cerr << "Universe<T>::createObjectRef : *iterOBJECTptr " << *iterOBJECTptr << endl;)
    DEBUG(cerr << "Universe<T>::createObjectRef : **iterOBJECTptr " << **iterOBJECTptr << endl;)
      
    delete &object;
    
    return **iterOBJECTptr; // return the pointer to OBJECT
    
  }
  else { // we have to add the point to the universe
    DEBUG(cerr << "Universe<T>::createObjectRef : NOT found ... " << endl;)
    DEBUG(cerr << "Universe<T>::createObjectRef : containerPoint3DptrlistC.push_back(&object);" << endl;)

    containerPoint3DptrlistC.push_back(&object);
  
    return object;
  }

}

// create a point by checking if it already exists in the universe
// DEPRECATED
template<typename T> Point3D<T> & Universe<T>::createPoint3Dref_BACKUP(T x,T y,T z) {
 
  DEBUG(cerr << "Universe<T>::createPoint3Dref" << endl;)

     
  Point3D<T> & pt3d = *(new Point3D<T>(x,y,z));

  DEBUG(cerr << "Universe<T>::createPoint3Dref : std::find_if ... " << endl;)
  // i check unicity of the point in Universe i.e to save memory and speed
  // i do not want to have two mathematically identical 3D points
  typename list< Point3D<T> *>::iterator iterP3Dptr =
    std::find_if(containerPoint3DptrlistC.begin(), containerPoint3DptrlistC.end(),
         // lambda in C++
              [&pt3d](Point3D<T> * pt3d_ptr_lambda_param) {
                          Point3D<T> & pt3d_lambda_param = *pt3d_ptr_lambda_param;                  
                          DEBUG(cerr << "Universe<T>::createPoint3Dref : in Lambda" << endl;)
                  //return  *pt3d_ptr_lambda_param == pt3d;
                  return  pt3d_lambda_param == pt3d;
              }
         );

  DEBUG(cerr << "Universe<T>::createPoint3Dref : bool found ... " << endl;)
  bool found = (iterP3Dptr != containerPoint3DptrlistC.end());

  
  if (found) {
    
    DEBUG(cerr << "Universe<T>::createPoint3Dref : found ... " << endl;)
    DEBUG(cerr << "Universe<T>::createPoint3Dref : *iterP3Dptr " << *iterP3Dptr << endl;)
    DEBUG(cerr << "Universe<T>::createPoint3Dref : **iterP3Dptr " << **iterP3Dptr << endl;)
      
    delete &pt3d;
    
    //return  static_cast<Point3D<T> &> (*iterP3Dptr); // return the pointer to Point3D
    //return  reinterpret_cast<Point3D<T> &> (*iterP3Dptr); // return the pointer to Point3D
    //return  static_cast<Point3D<T> &> (**iterP3Dptr); // return the pointer to Point3D
    
    return **iterP3Dptr; // return the pointer to Point3D
    
  }
  else { // we have to add the point to the universe
    DEBUG(cerr << "Universe<T>::createPoint3Dptr : NOT found ... " << endl;)
    DEBUG(cerr << "Universe<T>::createPoint3Dref : containerPoint3DptrlistC.push_back(&pt3d);" << endl;)

    containerPoint3DptrlistC.push_back(&pt3d);
    return pt3d;
      
  }

}

 
// create an object by checking if it already exist in the universe
// DEPRECATED
#define CREATE_OBJECT(FUNCTION_NAME,TYPE,CONTAINER,PARENTHESIS_ARGS,TYPED_PARAMS...) template<typename T> TYPE & Universe<T>::FUNCTION_NAME(TYPED_PARAMS) { \
  DEBUG(cerr << "Universe<T>::create" #TYPE "ref" << endl;)         \
  TYPE & object = *(new TYPE PARENTHESIS_ARGS); \
  DEBUG(cerr << "Universe<T>::create" #TYPE "ref : std::find_if ... " << endl;) \
  typename list< TYPE *>::iterator iterObjectptr = \
    std::find_if( CONTAINER.begin(), CONTAINER.end(), \
              [&object](TYPE * object_ptr_lambda_param) { \
                          TYPE & object_lambda_param = *object_ptr_lambda_param; \
                          DEBUG(cerr << "Universe<T>::create" #TYPE "ref : in Lambda" << endl;) \
                  return  object_lambda_param == object; \
              } \
         ); \
  DEBUG(cerr << "Universe<T>::create" #TYPE "ref : bool found ... " << endl;) \
  bool found = (iterObjectptr != CONTAINER.end()); \
  if (found) { \
    DEBUG(cerr << "Universe<T>::create" #TYPE "ref : found ... " << endl;) \
    DEBUG(cerr << "Universe<T>::create" #TYPE "ref : *iterObjectptr " << *iterObjectptr << endl;) \
    DEBUG(cerr << "Universe<T>::create" #TYPE "ref : **iterObjectptr " << **iterObjectptr << endl;) \
      delete &object; \
    return **iterObjectptr; \
  } \
  else { \
    DEBUG(cerr << "Universe<T>::create" #TYPE "ptr : NOT found ... " << endl;) \
    DEBUG(cerr << "Universe<T>::create" #TYPE "ref : CONTAINER.push_back(object_ptr);" << endl;) \
    CONTAINER.push_back(&object); \
    return object; \
  } \
}


//CREATE_OBJECT(createPoint3Dref,Point3D<T>,containerPoint3DptrlistC,(x,y,z),T x,T y,T z);

// create an object by checking if it already exist in the universe
// this a better version than CREATE_OBJECT, this macro use less parameters
#define CREATE_OBJECT_TYPE(TYPE,CONTAINER,PARENTHESIS_ARGS,TYPED_PARAMS...) template<typename T> TYPE<T> & Universe<T>::create##TYPE##ref(TYPED_PARAMS) { \
  DEBUG(cerr << "Universe<T>::create" #TYPE "ref" << endl;)         \
  TYPE<T> & object = *(new TYPE<T> PARENTHESIS_ARGS);   \
  DEBUG(cerr << "Universe<T>::create" #TYPE "ref : std::find_if ... " << endl;) \
  typename list< TYPE<T> *>::iterator iterObjectptr = \
    std::find_if( CONTAINER.begin(), CONTAINER.end(), \
              [&object](TYPE<T> * object_ptr_lambda_param) { \
                          TYPE<T> & object_lambda_param = *object_ptr_lambda_param; \
                          DEBUG(cerr << "Universe<T>::create" #TYPE "ref : in Lambda" << endl;) \
                  return  object_lambda_param == object; \
              } \
         ); \
  DEBUG(cerr << "Universe<T>::create" #TYPE "ref : bool found ... " << endl;) \
  bool found = (iterObjectptr != CONTAINER.end()); \
  if (found) { \
    DEBUG(cerr << "Universe<T>::create" #TYPE "ref : found ... " << endl;) \
    DEBUG(cerr << "Universe<T>::create" #TYPE "ref : *iterObjectptr " << *iterObjectptr << endl;) \
    DEBUG(cerr << "Universe<T>::create" #TYPE "ref : **iterObjectptr " << **iterObjectptr << endl;) \
      delete &object; \
    return **iterObjectptr; \
  } \
  else { \
    DEBUG(cerr << "Universe<T>::create" #TYPE "ptr : NOT found ... " << endl;) \
    DEBUG(cerr << "Universe<T>::create" #TYPE "ref : CONTAINER.push_back(object_ptr);" << endl;) \
    CONTAINER.push_back(&object); \
    return object; \
  } \
}

// DEPRECATED
//#define CONCATENATE(x , y) x##y

//CREATE_OBJECT_TYPE(Point3D,containerPoint3DptrlistC,(x,y,z),T x,T y,T z);


// create an object by checking if it already exist in the universe
// this another better version than CREATE_OBJECT, this macro use again less parameters
// DEPRECATED
#define CREATE_OBJECT_TYPED(TYPE,PARENTHESIS_ARGS,TYPED_PARAMS...)\
template<typename T> TYPE<T> & Universe<T>::create##TYPE##Reference(TYPED_PARAMS) { \
  DEBUG(cerr << "Universe<T>::create" #TYPE "Reference" << endl;)           \
  TYPE<T> & object = *(new TYPE<T> PARENTHESIS_ARGS);   \
  DEBUG(cerr << "Universe<T>::create" #TYPE "Reference : std::find_if ... " << endl;) \
  typename list< TYPE<T> *>::iterator iterObjectptr = \
    std::find_if( container##TYPE##ptrlistC.begin(), container##TYPE##ptrlistC.end(), \
              [&object](TYPE<T> * object_ptr_lambda_param) { \
                          TYPE<T> & object_lambda_param = *object_ptr_lambda_param; \
                          DEBUG(cerr << "Universe<T>::create" #TYPE "Reference : in Lambda" << endl;) \
                  return  object_lambda_param == object; \
              } \
         ); \
  DEBUG(cerr << "Universe<T>::create" #TYPE "Reference : bool found ... " << endl;) \
  bool found = (iterObjectptr != container##TYPE##ptrlistC.end()); \
  if (found) { \
    DEBUG(cerr << "Universe<T>::create" #TYPE "Reference : found ... " << endl;) \
    DEBUG(cerr << "Universe<T>::create" #TYPE "Reference : *iterObjectptr " << *iterObjectptr << endl;) \
    DEBUG(cerr << "Universe<T>::create" #TYPE "Reference : **iterObjectptr " << **iterObjectptr << endl;) \
      delete &object; \
    return **iterObjectptr; \
  } \
  else { \
    DEBUG(cerr << "Universe<T>::create" #TYPE "ptr : NOT found ... " << endl;) \
    DEBUG(cerr << "Universe<T>::create" #TYPE "Reference : container???.push_back(object_ptr);" << endl;) \
    container##TYPE##ptrlistC.push_back(&object); \
    return object; \
  } \
}

// example:  univ.createPoint3DReference(1,0,0);
CREATE_OBJECT_TYPED(Point3D,(x,y,z),T x,T y,T z);


// create a point by checking if it already exist in the universe
template<typename T> Point3D<T> * Universe<T>::createPoint3Dptr(T x,T y,T z) {
 
  DEBUG(cerr << "Universe<T>::createPoint3Dptr" << endl;)

  Point3D<T> * pt3d_ptr = new Point3D<T>(x,y,z);
  Point3D<T> & pt3d = *pt3d_ptr;
    
  
  DEBUG(cerr << "Universe<T>::createPoint3Dptr : std::find_if ... " << endl;)
  // i check unicity of the point in Universe i.e to save memory and speed
  // i do not want to have two mathematically identical 3D points
  typename list< Point3D<T> *>::iterator iterP3Dptr =
    std::find_if(containerPoint3DptrlistC.begin(), containerPoint3DptrlistC.end(),
         // lambda in C++
              [&pt3d](Point3D<T> * pt3d_ptr_lambda_param) {
                          Point3D<T> & pt3d_lambda_param = *pt3d_ptr_lambda_param;                  
                          DEBUG(cerr << "Universe<T>::createPoint3Dptr : in Lambda" << endl;)
                  //return  *pt3d_ptr_lambda_param == pt3d;
                  return  pt3d_lambda_param == pt3d;
              }
         );

  DEBUG(cerr << "Universe<T>::createPoint3Dptr : bool found ... " << endl;)
  bool found = (iterP3Dptr != containerPoint3DptrlistC.end());

  
  if (found) {
    
    DEBUG(cerr << "Universe<T>::createPoint3Dptr : found ... " << endl;)
    DEBUG(cerr << "Universe<T>::createPoint3Dptr : *iterP3Dptr " << *iterP3Dptr << endl;)
    DEBUG(cerr << "Universe<T>::createPoint3Dptr : **iterP3Dptr " << **iterP3Dptr << endl;)
      
    delete pt3d_ptr;
     
    //return  static_cast<Point3D<T> &> (*iterP3Dptr); // return the pointer to Point3D
    //return  reinterpret_cast<Point3D<T> &> (*iterP3Dptr); // return the pointer to Point3D
    //return  static_cast<Point3D<T> &> (**iterP3Dptr); // return the pointer to Point3D
    
    return *iterP3Dptr; // return the pointer to Point3D
    
  }
  else { // we have to add the point to the universe
    DEBUG(cerr << "Universe<T>::createPoint3Dptr : NOT found ... " << endl;)
    DEBUG(cerr << "Universe<T>::createPoint3Dptr : containerPoint3DptrlistC.push_back(pt3d_ptr);" << endl;)
    containerPoint3DptrlistC.push_back(pt3d_ptr);
    return pt3d_ptr;
  
      
  }

}

// params: point, edge length
template<typename T> void Universe<T>::createCube(Point3D<T> & p,T s) {

  // horizontal edges
  Point3D<T> & p2 = createPoint3DReflistC<Point3D<T>,T,T,T>(p.x+s,p.y,p.z); // bottom ,right x
  createEdge3DReflistC<Edge3D<T>,Point3D<T> &,Point3D<T> &>(p,p2);
  Point3D<T> & p3 = createPoint3DReflistC<Point3D<T>,T,T,T>(p.x+s,p.y+s,p.z); // bottom ,right x,left y
  createEdge3DReflistC<Edge3D<T>,Point3D<T> &,Point3D<T> &>(p2,p3);
  Point3D<T> & p4 = createPoint3DReflistC<Point3D<T>,T,T,T>(p.x,p.y+s,p.z); // bottom ,left y
  createEdge3DReflistC<Edge3D<T>,Point3D<T> &,Point3D<T> &>(p3,p4);
  createEdge3DReflistC<Edge3D<T>,Point3D<T> &,Point3D<T> &>(p,p4);

  Point3D<T> & ptop = createPoint3DReflistC<Point3D<T>,T,T,T>(p.x,p.y,p.z+s);
  Point3D<T> & p2top = createPoint3DReflistC<Point3D<T>,T,T,T>(p.x+s,p.y,ptop.z); // top ,right x
  createEdge3DReflistC<Edge3D<T>,Point3D<T> &,Point3D<T> &>(p,p2top);
  Point3D<T> & p3top = createPoint3DReflistC<Point3D<T>,T,T,T>(p.x+s,p.y+s,ptop.z); // top ,right x,left y
  createEdge3DReflistC<Edge3D<T>,Point3D<T> &,Point3D<T> &>(p2top,p3top);
  Point3D<T> & p4top = createPoint3DReflistC<Point3D<T>,T,T,T>(p.x,p.y+s,ptop.z); // top ,left y
  createEdge3DReflistC<Edge3D<T>,Point3D<T> &,Point3D<T> &>(p3top,p4top);
  createEdge3DReflistC<Edge3D<T>,Point3D<T> &,Point3D<T> &>(ptop,p4top);

  // vertical edges
  createEdge3DReflistC<Edge3D<T>,Point3D<T> &,Point3D<T> &>(p,ptop);
  createEdge3DReflistC<Edge3D<T>,Point3D<T> &,Point3D<T> &>(p2,p2top);
  createEdge3DReflistC<Edge3D<T>,Point3D<T> &,Point3D<T> &>(p3,p3top);
  createEdge3DReflistC<Edge3D<T>,Point3D<T> &,Point3D<T> &>(p4,p4top);
  
}


// DEPRECATED
//template Point3D<float> & Universe<float>::createObjectRef(float,float,float) ; // works too
template Point3D<float> & Universe<float>::createObjectRef<Point3D<float>,float,float,float>(float,float,float) ;
//template int Universe<float>::createObjectRef<int,float,float,float>(float,float,float) ;



template <typename U>
std::ostream&  operator<< (std::ostream &out, Universe<U> &u)
{
  
  out << "Universe :"  
      << &u
      << " "
    ;
  
  return out;
  
}




template class Universe<float>;


// for tests
//template int Universe<float>::GetMax( int,int ) ; // works too
template int Universe<float>::GetMax<int,float>( int,int );



// call by : univ.createPoint3DReflistC<Point3D<float>,float,float,float>(1,0,0);
template Point3D<float> & Universe<float>::createPoint3DReflistC<Point3D<float>,float,float,float>(float,float,float) ;

template Edge3D<float> & Universe<float>::createEdge3DReflistC<Edge3D<float>,Point3D<float>&,Point3D<float>&>(Point3D<float>&,Point3D<float>&) ;



template Point3D<float> & Universe<float>::createPoint3DRefvectorC<Point3D<float>,float,float,float>(float,float,float) ;

template Vector3D<float> & Universe<float>::createVector3DRefvectorC<Vector3D<float>,float,float,float>(float,float,float) ;


template std::ostream&  operator<<  (std::ostream &, const Universe<float> &); // does not work

(base) albedo-2:vision3D mattei$ make COMPILING Universe.cpp g++ -c -o Universe.o Universe.cpp -Wall -std=c++17 -I. -DDEBUG_BUILD -DDISPLAY_CONSTRUCTOR -DCHECK_MEMORY Universe.cpp:468:25: error: explicit instantiation of undefined function template 'operator<<' template std::ostream& operator<< (std::ostream &, const Universe &); // does not work ^ ./Universe.hpp:109:39: note: explicit instantiation refers here template std::ostream& operator<< (ostream &, const Universe &); // does not work !!! ^ 1 error generated. make: *** [Universe.o] Error 1

Communication protocol in c++

I would like to implement communication protocol in C++ with the following conditions, can someone help/suggest me on how to implement it.

Basic conditions:

  • Packet size is fixed to 12 bytes
  • Every packet starts with a “magic” header.
  • Byte order of data in the packet is from most significant to least significant
  • You cannot assume that all incoming bytes are correct, consistent packets.

There may be other types of data between packets, for example: [packet] [packet] [control sequence] [packet] [spurious bytes] [control sequence] [packet]

Packet layout contains following information: Magic header[4B] 0xABBACFFC, Secondary Header[2B], Reserved[1B] 0xFF, Payload [4B], checksum [1B]

Secondary header layout: Protocol version [3 bit], Subsystem ID [5 bit], Component ID [5 bit], Telemetry type[3 bit]

Magic header:

  1. 0xABBACFFC marks the start of a packet Secondary header:
  2. Protocol versions:
  3. Supported protocol versions: 1, 2 Both versions have the same packet layout.
  4. List item
  5. Valid subsystem IDs:
  6. 1 - AOCS
  7. 3 - CDH
  8. 5 - COM

Valid component IDs for each subsystem:

  1. AOCS: 20, 21, 22, 23, 30, 31
  2. CDH: 0
  3. COM: 1, 2, 10, 20

Valid telemetry type: 1 - temperature (implies data of type IEEE 754 single precision floating-point)

Reserved field:

  1. One byte reserved for future protocol expansion.
  2. Must be set to 0xFF

Payload:

  • If telemetry types is ‘1’ (temperature), the value in the 4 bytes of payload is IEEE 754 single precision floating-point.

Checksum:

  • Simple exclusive-or (xor) of all bytes from the start of secondary header to the end of payload (including reserved field).

Interface description: For the exemplary code block fragment, I want to design and implement Parser class. tlm_parser.h:

class Parser {
// Implement me
};

tlm.h:

typedef struct {
    uint8_t subsys_id;
    uint8_t compo_id;
    Float temperature;
} CompoTlm_t;

tlm_proc.cpp:

while ( 1 ) {
    while (iface.existRcvData()) {
        uint8_t byte = iface.getByte();
        // Parse incoming bytes and detect packet
        if (parser.detectPkt(byte)) {
            // One, correct packet has been detected
            CompoTlm_t tlm = {};
            int err = parser.extractData(tlm);
            if (err == 0 ) {
                // Pass telemetry info to the upper layer
                system.tlm.update(tlm);
            } else {
                // Error handling, etc.
                ...
                ...
        }
    }
}
system.time.sleep_ms( 100 );
}
  1. iface is an object of a class that is used to communicate with the peripheral devices
  2. existRcvData() method returns true if there are bytes in the Rx FIFO
  3. getByte() method fetches one byte from the Rx FIFO
  4. parser is an object of a class that you are asked to implement
  5. system is an object of a class that communicates with the hypothetical OS
  6. tlm is an object used to process system’s telemetry.
  7. update() method can be used to send latest telemetry to the system control Communication protocol description

What is the best data structure you will use to store the user profile [closed]

What is the best data structure you will use to store the user profile and their connected friends on Facebook from this data structure (ArrayList , linkedList , Queue) ?? Hint: I can't use the Grapgh.

c++11 template class return type

a simple class

   struct Test{
        void display(int x)
        {
           printf("%d\n", x);
        }
    };

c++11

template<class F, class... Args>
auto enqueue(F&& f, Args&&... args) -> std::future<decltype(f(args...))>{

    auto task = std::make_shared<std::packaged_task<decltype(f(args...)())>>(
        std::bind(std::forward<F>(f), std::forward<Args>(args)...)
    );
    return task->get_future();
}

call it just use (cls is the object of the class of the template function above)

Test test;
cls->enqueue(&Test::display, &test, 0);

the comipler error

candidate template ignored: substitution failure 
[with F = void (TestMem::*)(int), Rest = <TestMem *, int>]: called object type 'void (TestMem::*)(int)' is not a function or function pointer
        auto enqueue(F && f, Rest&&... rest) ->std::future<decltype(f(rest...))> {

above works well on a non class member function, can some one give a fix on c++11

c++14 works fine, but my project needs c++11

template<class F, class... Args>
auto enqueue(F&& f, Args&&... args) {

    using return_type = typename std::result_of<F(Args...)>::type;

    auto task = std::make_shared<std::packaged_task<return_type()>>(
        std::bind(std::forward<F>(f), std::forward<Args>(args)...)
    );
    return task->get_future();
}

Need to press enter for my console C++ code to continue executing on windows cmd

I have written a c++ code that sends logs to the console using cout. the issue is that i have sometimes to press enter so my code can continue executing and display next logs. for information, there is absolutely no input request in my code (cin or other).

I tried to use '\n' instead of endl. I also disabled inputs using this function:

FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));

but the issue still persists (the console still waits for me to press enter to continue executing the code...). Could you please help?

thanks in advance

unique_ptr returns junk values with move semanitics

I have the generic class which can store a value and a type of the value encoded as a string.

#include <iostream>
#include <string>
#include <memory>
#include <cassert>

struct IValueHolder 
{
    virtual ~IValueHolder() = default;
    virtual const std::string& getType() = 0;
    virtual void setType(const std::string& t_type) = 0;
};

template<class T>
class ValueHolder : public IValueHolder
{
private:
    T m_value;
    std::string m_type;
public:

    ValueHolder(T t_value) : m_value(t_value){}
    
    virtual const std::string& getType() override
    {
        return m_type;
    }

    virtual void setType(const std::string& t_type) override
    {
        m_type= t_type;
    }

    const T& getValue() const
    {
        return m_value;
    }
};

std::unique_ptr<IValueHolder> build_int_property()
{
    auto p32{ std::make_unique<ValueHolder<int32_t>>(0) };
    p32->setType("int32");
    return std::move(p32);
}

int main()
{

    auto v32 = dynamic_cast<ValueHolder<int32_t>*>(build_int_property().get());

    assert(v32->getValue() == 0); // FAILS 
    assert(v32->getType() == "int32"); // FAILS

    return EXIT_SUCCESS;
}

And I have another utility function build_int_property which builds an integer property. But unfortunately, the tests fail. Can anyone explain what is going wrong here?

unresolved overloaded function type>, int, main()::

I don't know how to pass the method with a lambda parameter into the std::thread. My code sample as below:

using namespace std;
#include <bits/stdc++.h>
#include <iostream>
#include <string>
#include <thread>     
template<typename var>
void show(int a, var pf)
{
    for(int i = 0; i < 10; pf(i))
    {
        cout << "i = " << i << endl;
    }
}

int main()
{
    int int_test = 10;
    auto func = [](int &x)->int{ return x = x + 1; };
    show(10, func);
    std::thread a(&show, 10, func);
    a.join();
}

Compile with the command: g++ ThreadLambda.cpp -pthread -std=c++11 -o test;

And the error show:

ThreadLambda.cpp:149:66: error: no matching function for call to ‘std::thread::thread(<unresolved overloaded function type>, int, main()::<lambda(int&)>)’
     std::thread a(&show, 10, [](int &x)->int{ return x = x + 1; });

samedi 29 mai 2021

getting this error: [Warning] exteded initializer lists only avalable with -std=c++11 or -std=gnu++11 [duplicate]

I did include list but i am getting this error! can someone please help me? i dont understand whats going on. Help is really aprreciated!

#include <iostream>
#include <iomanip>
#include <list>
using namespace std;

class YouTubeChannel{
public:         
    string Name;
    string OwnerName;
    int SubscribersCount;
    list<string> PublishedVideoTitles;  //list have been included
};

int main(){
    
    YouTubeChannel ytChannel;
    ytChannel.Name="CodeBeauty";
    ytChannel.OwnerName="Saldina";
    ytChannel.SubscribersCount=1800;
    ytChannel.PublishedVideoTitles={"C++ for beginners video 1", "HTML & CSS video 1", "C++ OOP Video 
    1"};  //not working even tho list included
    
    cout<<"Name: "<<ytChannel.Name<<endl;
    cout<<"Name: "<<ytChannel.OwnerName<<endl;
    cout<<"Name: "<<ytChannel.SubscribersCount<<endl;
    
    cout<<"Videos: \n";
    for(string videoTitle: ytChannel.PublishedVideoTitles){
        cout<<videoTitle<<endl;
    }
    
    system("pause>0");
    return 0;
}

expected class-name before { token in multi file project

I am a begginer in C++ . I am coding a multi file project and I encountered a bug I don't know how to work around . I am inherting from a base class of ModelUser which has the general info for a user account with a class that Is called NUser ,I am basically using polymorphism here. the error :


In file included from Score.hpp:5,
                 from Recipe.hpp:6,
                 from UserModel.hpp:6,
                 from Chef.hpp:1,
                 from Menu.hpp:6,
                 from main.cpp:2:
Normal_User.hpp:11:1: error: expected class-name before ‘{’ token
   11 | {
      | ^
make: *** [Makefile:7: main.o] Error 1


My code stops compiling when it hits class Nuser : public UserModel and tells me It needs a class name before the in line 11 of Normal_User.hpp ' } ' . I searched around for the cause of this error and it seems to ambigious but what I Found out was that the class I am inheriting from is not defined at the point of the file the error occurs in . I don't know the reason why the class I inherit from is not included at the time of compilation of this file , I have used the class in other parts of the code and at the start of main , I have include guards and I have tested around to see if they are causing the problem but I dont really know .

then I tried to do a forward decleration which I know won't work because I will get an incomplete type error . SO I am kind of stuck here , here is a look at my files , I am using Polymorphism from a base user for a Normal user when I get this error. I havent included certain files ,feel free to comment if you need any other source.

Should i Change my code design here , because I don't see where I have gone wrong Normal_User.hpp

#include <vector>
#include <iostream>
#include <string>
#include "UserModel.hpp"
#ifndef _NORMAL_USER_HPP_
#define _NORMAL_USER_HPP_
#include "Recipe.hpp"
class Recipe;
using namespace std;
class Nuser : public UserModel
{
public:
    Nuser(vector<string> &commands, int user_size);
    void see_recipes(vector<Recipe *> recipes);
private:
};
#endif

UserModel.hpp

#include <vector>
#include <iostream>
#include <string>
#ifndef _USER_MODEL_HPP_
#define _USER_MODEL_HPP_
#include "Recipe.hpp"
using namespace std;
class Recipe;
class UserModel
{
public:
    string get_username();
    string get_password();
    bool get_logged_in();
    void user_logout();
    void user_login(bool value);
    UserModel(vector<string> &commands, int user_size);
    virtual void see_recipes(vector<Recipe*> recipes) = 0;
private:
    int primary_key;
    bool logged_in;
    string username;
    string password;
};
#endif

makefile

CC= g++
CXXFLAS = g++ -std=c++11 -g 
LDBFLAGS =
output: main.o outerior_functions.o UserModel.o Normal_User.o  Menu.o Chef.o Recipe.o  Exception.o
    g++ -std=c++11 -g main.o UserModel.o  Exception.o outerior_functions.o Menu.o Normal_User.o Chef.o Recipe.o -o output
main.o: outerior_functions.cpp main.cpp outerior_functions.hpp
    g++ -std=c++11 -g   -c main.cpp -o main.o 
UserModel.o: UserModel.cpp UserModel.hpp main_header.hpp
    g++ -std=c++11 -g   -c UserModel.cpp -o UserModel.o
outerior_functions.o: outerior_functions.cpp outerior_functions.hpp
    g++ -std=c++11 -g   -c outerior_functions.cpp -o outerior_functions.o
Exception.o: Exception.cpp Exception.hpp main_header.hpp
    g++ -std=c++11 -g   -c Exception.cpp -o Exception.o
chef.o: chef.cpp chef.hpp main_header.hpp
    g++ -std=c++11 -g   -c chef.cpp -o chef.o
Recipe.o: Recipe.cpp Recipe.hpp main_header.hpp
    g++ -std=c++11 -g   -c Recipe.cpp -o Recipe.o
Menu.o: Menu.cpp Menu.hpp main_header.hpp
    g++ -std=c++11 -g   -c Menu.cpp -o Menu.o
Normal_User.o: Normal_User.cpp Recipe.hpp Normal_User.hpp User_Model.hpp main_header.hpp 
    g++ -std=c++11 -g   -c Normal_User.cpp -o Normal_User.o
.PHONY: clean
clean:
    rm *.o output

Menu.hpp (Kind of my mother class )



#include <vector>
#include <string>
#include <iostream>
#ifndef _MENU_HPP_
#define _MENU_HPP_
#include "Chef.hpp"
#include "Normal_User.hpp"
#include "UserModel.hpp"
#include "outerior_functions.hpp"
using namespace std;
class Menu
{
public:
    void direct_command(vector<string> &commands);
    void signup(vector<string> &commands);
    void login(vector<string> &commands);
    void check_duplication(string &username);
    void handle_signup(vector<string> &commands);
    void handle_login(vector<string> &commands);
    UserModel *user_search(string username);
    void logout();
    Menu();

private:
    vector<UserModel *> users;
    vector<Recipe *> recipes;
    UserModel *current_user;
};
#endif

Getting the length of an array of undetermined size at compile time

I was just messing around with Compiler Explorer a bit... I was asking myself why there is no lenth() function in C++ to determine the size of an array at compile time, because in my opinion it should be easy to write. But apparently it's not that easy. My idea was something like this:

#include <iostream>

using namespace std;

void print_all(const int num[], const size_t n)
{
    for (size_t i = 0; i < n; ++i)
        cout << num[i] << endl;
}

template <class T, size_t N>
constexpr size_t  length(T (&arr)[N])
{
    return N;
}

int main()
{
    constexpr int a[] { 1, 2, 3, 4 };
    print_all(a, length(a));
}

However, according to godbolt.org with clang 11.0.1, x86-64, this will be compiled into the following:

main:                                   # @main
        ...
        call    unsigned long length<int const, 4ul>(int const (&) [4ul])
        mov     rdi, qword ptr [rbp - 24]       # 8-byte Reload
        mov     rsi, rax
        call    print_all(int const*, unsigned long)
        xor     eax, eax
        add     rsp, 32
        pop     rbp
        ret
unsigned long length<int const, 4ul>(int const (&) [4ul]):             # @unsigned long length<int const, 4ul>(int const (&) [4ul])
        push    rbp
        mov     rbp, rsp
        mov     qword ptr [rbp - 8], rdi
        mov     eax, 4
        pop     rbp
        ret

So it's not inlined.

Is there a way to get a convenience function with zero runtime cost?

PS: I am not interested in this because I actually want to use such a function. I know that std::array or std::span would be way better solutions in almost all cases and that the raw loop in print_all is fishy etc. I am asking this because I want to improve my understanding of C++ and because arrays of undetermined size occur 'in the wild.' Also I am aware that I could use sizeof(a)/sizeof(a[0]), but I was thinking that there should be a way to get things like this done using templates and constexpr because that's somehow what they are for (creating convenience that can be paid for at compile time).

How to Point a base class pointer array to a derived class object on a specific index

How can I point pointer array of class A at index 1 to a derived class object. so when I write pointer[1].print(), it calls the print function from class B. (its index 0 should remain pointing the the object of type A)

#include <iostream>
using namespace std;
class A
{
protected:
string name;
public:
A()
{
name="A";
}
virtual void print()
{
cout<< name;
}
};


class B : public A
{

public:
B()
{
name="B";
}
void print()
{
cout<< name;
}
};

int main()
{
A *pointer=new A [2];
pointer[0].print(); //prints A

//now I want index 1 to be pointed to object of child class B
//so when I write pointer[1].print()
// "B" is printed. 
}

Visual studio saying that std has no member move(std::move) . Why is it giving an error?

Below is my code: Main.cpp

 #include "Integer.h"
    int main() {
           //1st object made
           Integer i1(5);
           Integer i2(std::move(i1));
           return 0;
    }

I have Visual Studio 2019

c++ STL using vector

I defined a ThreadSafe List and I want to declear a vector to save some ThreadSafe list, but when I initialized the vector using resize, I got some error.

The SafeList I defined:

template<class T>
class SafeQueue{
public:
    SafeQueue() {}
    SafeQueue(const SafeQueue & sq) = delete;
    SafeQueue & operator = (const SafeQueue & sq) = delete;

private:
    std::queue<T> queue_;
    std::mutex mutex_;

And the Initialization code is:

for (auto & p : timer_) {
    // p type: std::vector<SafeContainer::SafeList<TimerNodePtr> >
    p.resize(SHIFT);
}

And the error information followed:

/usr/include/c++/9/bits/stl_uninitialized.h: In instantiation of ‘_ForwardIterator std::uninitialized_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = std::move_iterator<SafeContainer::SafeList<std::shared_ptr<Timer::TimerNode> >*>; _ForwardIterator = SafeContainer::SafeList<std::shared_ptr<Timer::TimerNode> >*]’:
/usr/include/c++/9/bits/stl_uninitialized.h:307:37:   required from ‘_ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, std::allocator<_Tp>&) [with _InputIterator = std::move_iterator<SafeContainer::SafeList<std::shared_ptr<Timer::TimerNode> >*>; _ForwardIterator = SafeContainer::SafeList<std::shared_ptr<Timer::TimerNode> >*; _Tp = SafeContainer::SafeList<std::shared_ptr<Timer::TimerNode> >]’
/usr/include/c++/9/bits/stl_uninitialized.h:329:2:   required from ‘_ForwardIterator std::__uninitialized_move_if_noexcept_a(_InputIterator, _InputIterator, _ForwardIterator, _Allocator&) [with _InputIterator = SafeContainer::SafeList<std::shared_ptr<Timer::TimerNode> >*; _ForwardIterator = SafeContainer::SafeList<std::shared_ptr<Timer::TimerNode> >*; _Allocator = std::allocator<SafeContainer::SafeList<std::shared_ptr<Timer::TimerNode> > >]’
/usr/include/c++/9/bits/vector.tcc:659:48:   required from ‘void std::vector<_Tp, _Alloc>::_M_default_append(std::vector<_Tp, _Alloc>::size_type) [with _Tp = SafeContainer::SafeList<std::shared_ptr<Timer::TimerNode> >; _Alloc = std::allocator<SafeContainer::SafeList<std::shared_ptr<Timer::TimerNode> > >; std::vector<_Tp, _Alloc>::size_type = long unsigned int]’
/usr/include/c++/9/bits/stl_vector.h:937:4:   required from ‘void std::vector<_Tp, _Alloc>::resize(std::vector<_Tp, _Alloc>::size_type) [with _Tp = SafeContainer::SafeList<std::shared_ptr<Timer::TimerNode> >; _Alloc = std::allocator<SafeContainer::SafeList<std::shared_ptr<Timer::TimerNode> > >; std::vector<_Tp, _Alloc>::size_type = long unsigned int]’
/home/ctrlz/workSpace/MyServer/src/Timer.cpp:8:23:   required from here
/usr/include/c++/9/bits/stl_uninitialized.h:127:72: error: static assertion failed: result type must be constructible from value type of input range
  127 |       static_assert(is_constructible<_ValueType2, decltype(*__first)>::value,

Can someone help me? Thanks!


minimal reproducible example as followed:

#include <vector>
#include <queue>
#include <mutex>
template<class T>
class SafeQueue{
public:
    SafeQueue() {}
    SafeQueue(const SafeQueue & sq) = delete;
    SafeQueue & operator = (const SafeQueue & sq) = delete;


private:
    std::queue<T> queue_;
    std::mutex mutex_;
};

int main() {
    std::vector<SafeQueue<int> > list;
    list.resize(5);
}

How does static_cast

I read std::move() does the same thing*

How read particular event log entries using c++?

How to get particular Event log entries from Event log using Event ID

      I have tried ReadEventlog samples but it gets all the event i need to run a while loop to filter.

Instead of that kindly let me know how we can achieve it using any direct method or query using C++.

     its like Example if we have 3000 events out of that 1000 event has Event id:150 .

how we can query it.

Code i have tried :

        while (ERROR_SUCCESS == status)
{
    if (!ReadEventLog(hEventLog, 
        EVENTLOG_SEQUENTIAL_READ | EVENTLOG_BACKWARDS_READ,
        0, 
        pBuffer,
        dwBytesToRead,
        &dwBytesRead,
        &dwMinimumBytesToRead))
    {
          ....
    }
 }

vendredi 28 mai 2021

Why is it displaying 13 and not 15?

This is the unary operator problem I am facing, and I fail to understand why VSCode gives output 8,13 when turbo c gives out the answer 8,15?

#include<bits/stdc++.h>
using namespace std;
int main()
{
   int a;
    a = 2;
    cout<<++a + ++a;              //This is displaying 8 which is understood
    
    a = 2;
    cout<<endl<<++a + ++a + ++a;  //Why is this displaying 13, shouldn't it be 5+5+5=15?
}

Polymorphism and containers [duplicate]

I have a base class Drawable that serves as an interface and has several other classes that inherit from it. Now I want to create instances of those child classes and add them to a container so that i can iterate over them and call the draw function.

#include <vector>
#include <string>

struct Drawable
{
public:
    std::string name;
    virtual void draw() = 0;
    Drawable() = default;
    virtual ~Drawable(){};
    Drawable(Drawable &other) = default;
    Drawable(Drawable &&other) = default;
    Drawable &operator=(Drawable &&other) = default;
};

bool operator==(const Drawable &lhs, const Drawable &rhs)
{
    return lhs.name == rhs.name;
}

bool operator!=(const Drawable &lhs, const Drawable &rhs)
{
    return !(lhs == rhs);
}

struct Square : public Drawable
{
    std::string name;
    Square(std::string name)
    {
        this->name = name;
    }
    void draw()
    {
        /* Some logic*/
    }
};

int main()
{
    Square reddy("reddy");

    std::vector<Drawable> drawables;

    drawables.push_back(reddy);
}

I get this error message

error: 
      allocating an object of abstract class type 'Drawable'
            ::new((void*)__p) _Up(_VSTD::forward<_Args>(__args)...);

Which happens because vector is trying to allocate space for a Drawable (which it can't because it's an abstract class). But how would i do this? None of the tutorials on polymorphism that i found covered something like this. Or am I searching for the wrong thing?

undefined reference to `napi_create_function', compiled using cmake

I'm trying to compile a machine learning code written in c++ and connecting it to NodeJS using n-api, I have written the NAPI function in one of the files, and defined additional dependencies in CMake.

Installed
'node-addon-api': '^3.0.0'
'cmake-js':'^6.1.0'

error

> cmake-js compile
 
[
  '/usr/bin/node',
  '/home/nishant/Documents/demo/node_modules/.bin/cmake-js',
  'compile'
]
info TOOL Using Unix Makefiles generator.
info CMD BUILD
info RUN cmake --build "/home/nishant/Documents/demo/build" --config Release
Consolidate compiler generated dependencies of target mobilenetknn
[ 60%] Built target mobilenetknn
Consolidate compiler generated dependencies of target program
[ 80%] Linking CXX executable program
CMakeFiles/program.dir/src/program.cpp.o: In function `Init(Napi::Env, Napi::Object)':
program.cpp:(.text+0x6b): undefined reference to `napi_create_function'
program.cpp:(.text+0xb8): undefined reference to `napi_create_symbol'
program.cpp:(.text+0xd3): undefined reference to `napi_create_external'
program.cpp:(.text+0x10f): undefined reference to `napi_define_properties'
program.cpp:(.text+0x133): undefined reference to `napi_create_string_utf8'
program.cpp:(.text+0x14a): undefined reference to `napi_set_property'
CMakeFiles/program.dir/src/program.cpp.o: In function `classAddTrainModel(Napi::CallbackInfo const&)':
program.cpp:(.text+0x268): undefined reference to `napi_coerce_to_number'
program.cpp:(.text+0x287): undefined reference to `napi_get_value_int32'
program.cpp:(.text+0x33a): undefined reference to `napi_get_element'
program.cpp:(.text+0x35d): undefined reference to `napi_get_element'
program.cpp:(.text+0x380): undefined reference to `napi_get_value_string_utf8'
program.cpp:(.text+0x3f7): undefined reference to `napi_get_value_string_utf8'
program.cpp:(.text+0x415): undefined reference to `napi_get_value_string_utf8'
program.cpp:(.text+0x48c): undefined reference to `napi_get_value_string_utf8'
program.cpp:(.text+0x8b8): undefined reference to `napi_create_double'
program.cpp:(.text+0xb55): undefined reference to `napi_get_undefined'
program.cpp:(.text+0xb7e): undefined reference to `napi_get_undefined'
program.cpp:(.text+0xbae): undefined reference to `napi_get_undefined'
CMakeFiles/program.dir/src/program.cpp.o: In function `Napi::Error::~Error()':
program.cpp:(.text._ZN4Napi5ErrorD2Ev[_ZN4Napi5ErrorD5Ev]+0x46): undefined reference to `napi_delete_reference'
CMakeFiles/program.dir/src/program.cpp.o: In function `Napi::AsyncContext::~AsyncContext()':
program.cpp:(.text._ZN4Napi12AsyncContextD2Ev[_ZN4Napi12AsyncContextD5Ev]+0x15): undefined reference to `napi_async_destroy'
CMakeFiles/program.dir/src/program.cpp.o: In function `Napi::AsyncContext::~AsyncContext()':
program.cpp:(.text._ZN4Napi12AsyncContextD0Ev[_ZN4Napi12AsyncContextD5Ev]+0x19): undefined reference to `napi_async_destroy'
CMakeFiles/program.dir/src/program.cpp.o: In function `Napi::Error::~Error()':
program.cpp:(.text._ZN4Napi5ErrorD0Ev[_ZN4Napi5ErrorD5Ev]+0x39): undefined reference to `napi_delete_reference'
CMakeFiles/program.dir/src/program.cpp.o: In function `Napi::Error::Fatal(char const*, char const*)':
program.cpp:(.text._ZN4Napi5Error5FatalEPKcS2_[_ZN4Napi5Error5FatalEPKcS2_]+0x12): undefined reference to `napi_fatal_error'
CMakeFiles/program.dir/src/program.cpp.o: In function `Napi::CallbackScope::~CallbackScope()':
program.cpp:(.text._ZN4Napi13CallbackScopeD2Ev[_ZN4Napi13CallbackScopeD5Ev]+0x14): undefined reference to `napi_close_callback_scope'
CMakeFiles/program.dir/src/program.cpp.o: In function `Napi::CallbackScope::~CallbackScope()':
program.cpp:(.text._ZN4Napi13CallbackScopeD0Ev[_ZN4Napi13CallbackScopeD5Ev]+0x14): undefined reference to `napi_close_callback_scope'
CMakeFiles/program.dir/src/program.cpp.o: In function `Napi::Error::New(napi_env__*)':
program.cpp:(.text._ZN4Napi5Error3NewEP10napi_env__[_ZN4Napi5Error3NewEP10napi_env__]+0x30): undefined reference to `napi_get_last_error_info'
program.cpp:(.text._ZN4Napi5Error3NewEP10napi_env__[_ZN4Napi5Error3NewEP10napi_env__]+0x45): undefined reference to `napi_is_exception_pending'
program.cpp:(.text._ZN4Napi5Error3NewEP10napi_env__[_ZN4Napi5Error3NewEP10napi_env__]+0x84): undefined reference to `napi_create_string_utf8'
program.cpp:(.text._ZN4Napi5Error3NewEP10napi_env__[_ZN4Napi5Error3NewEP10napi_env__]+0xbd): undefined reference to `napi_create_error'
program.cpp:(.text._ZN4Napi5Error3NewEP10napi_env__[_ZN4Napi5Error3NewEP10napi_env__]+0x10b): undefined reference to `napi_create_reference'
program.cpp:(.text._ZN4Napi5Error3NewEP10napi_env__[_ZN4Napi5Error3NewEP10napi_env__]+0x141): undefined reference to `napi_get_and_clear_last_exception'
program.cpp:(.text._ZN4Napi5Error3NewEP10napi_env__[_ZN4Napi5Error3NewEP10napi_env__]+0x170): undefined reference to `napi_create_type_error'
program.cpp:(.text._ZN4Napi5Error3NewEP10napi_env__[_ZN4Napi5Error3NewEP10napi_env__]+0x1ef): undefined reference to `napi_delete_reference'
CMakeFiles/program.dir/src/program.cpp.o: In function `Napi::HandleScope::~HandleScope()':
program.cpp:(.text._ZN4Napi11HandleScopeD2Ev[_ZN4Napi11HandleScopeD5Ev]+0xc): undefined reference to `napi_close_handle_scope'
CMakeFiles/program.dir/src/program.cpp.o: In function `Napi::Error::ThrowAsJavaScriptException() const':
program.cpp:(.text._ZNK4Napi5Error26ThrowAsJavaScriptExceptionEv[_ZNK4Napi5Error26ThrowAsJavaScriptExceptionEv]+0x28): undefined reference to `napi_open_handle_scope'
program.cpp:(.text._ZNK4Napi5Error26ThrowAsJavaScriptExceptionEv[_ZNK4Napi5Error26ThrowAsJavaScriptExceptionEv]+0x43): undefined reference to `napi_get_reference_value'
program.cpp:(.text._ZNK4Napi5Error26ThrowAsJavaScriptExceptionEv[_ZNK4Napi5Error26ThrowAsJavaScriptExceptionEv]+0x59): undefined reference to `napi_throw'
program.cpp:(.text._ZNK4Napi5Error26ThrowAsJavaScriptExceptionEv[_ZNK4Napi5Error26ThrowAsJavaScriptExceptionEv]+0x6c): undefined reference to `napi_close_handle_scope'
CMakeFiles/program.dir/src/program.cpp.o: In function `Napi::details::CallbackData<Napi::Number (*)(Napi::CallbackInfo const&), Napi::Number>::Wrapper(napi_env__*, napi_callback_info__*)':
program.cpp:(.text._ZN4Napi7details12CallbackDataIPFNS_6NumberERKNS_12CallbackInfoEES2_E7WrapperEP10napi_env__P20napi_callback_info__[_ZN4Napi7details12CallbackDataIPFNS_6NumberERKNS_12CallbackInfoEES2_E7WrapperEP10napi_env__P20napi_callback_info__]+0x65): undefined reference to `napi_get_cb_info'
program.cpp:(.text._ZN4Napi7details12CallbackDataIPFNS_6NumberERKNS_12CallbackInfoEES2_E7WrapperEP10napi_env__P20napi_callback_info__[_ZN4Napi7details12CallbackDataIPFNS_6NumberERKNS_12CallbackInfoEES2_E7WrapperEP10napi_env__P20napi_callback_info__]+0xb7): undefined reference to `napi_get_cb_info'
CMakeFiles/program.dir/src/program.cpp.o: In function `Napi::EscapableHandleScope::~EscapableHandleScope()':
program.cpp:(.text._ZN4Napi20EscapableHandleScopeD2Ev[_ZN4Napi20EscapableHandleScopeD5Ev]+0xc): undefined reference to `napi_close_escapable_handle_scope'
CMakeFiles/program.dir/src/program.cpp.o: In function `Napi::AsyncWorker::OnError(Napi::Error const&)':
program.cpp:(.text._ZN4Napi11AsyncWorker7OnErrorERKNS_5ErrorE[_ZN4Napi11AsyncWorker7OnErrorERKNS_5ErrorE]+0x46): undefined reference to `napi_get_reference_value'
program.cpp:(.text._ZN4Napi11AsyncWorker7OnErrorERKNS_5ErrorE[_ZN4Napi11AsyncWorker7OnErrorERKNS_5ErrorE]+0x71): undefined reference to `napi_get_reference_value'
program.cpp:(.text._ZN4Napi11AsyncWorker7OnErrorERKNS_5ErrorE[_ZN4Napi11AsyncWorker7OnErrorERKNS_5ErrorE]+0x90): undefined reference to `napi_open_escapable_handle_scope'
program.cpp:(.text._ZN4Napi11AsyncWorker7OnErrorERKNS_5ErrorE[_ZN4Napi11AsyncWorker7OnErrorERKNS_5ErrorE]+0xb3): undefined reference to `napi_get_reference_value'
program.cpp:(.text._ZN4Napi11AsyncWorker7OnErrorERKNS_5ErrorE[_ZN4Napi11AsyncWorker7OnErrorERKNS_5ErrorE]+0xde): undefined reference to `napi_call_function'
program.cpp:(.text._ZN4Napi11AsyncWorker7OnErrorERKNS_5ErrorE[_ZN4Napi11AsyncWorker7OnErrorERKNS_5ErrorE]+0xfa): undefined reference to `napi_is_exception_pending'
program.cpp:(.text._ZN4Napi11AsyncWorker7OnErrorERKNS_5ErrorE[_ZN4Napi11AsyncWorker7OnErrorERKNS_5ErrorE]+0x11c): undefined reference to `napi_get_reference_value'
program.cpp:(.text._ZN4Napi11AsyncWorker7OnErrorERKNS_5ErrorE[_ZN4Napi11AsyncWorker7OnErrorERKNS_5ErrorE]+0x163): undefined reference to `napi_escape_handle'
program.cpp:(.text._ZN4Napi11AsyncWorker7OnErrorERKNS_5ErrorE[_ZN4Napi11AsyncWorker7OnErrorERKNS_5ErrorE]+0x17a): undefined reference to `napi_close_escapable_handle_scope'
CMakeFiles/program.dir/src/program.cpp.o: In function `Napi::AsyncWorker::OnOK()':
program.cpp:(.text._ZN4Napi11AsyncWorker4OnOKEv[_ZN4Napi11AsyncWorker4OnOKEv]+0x6f): undefined reference to `napi_get_reference_value'
program.cpp:(.text._ZN4Napi11AsyncWorker4OnOKEv[_ZN4Napi11AsyncWorker4OnOKEv]+0x93): undefined reference to `napi_open_escapable_handle_scope'
program.cpp:(.text._ZN4Napi11AsyncWorker4OnOKEv[_ZN4Napi11AsyncWorker4OnOKEv]+0xb6): undefined reference to `napi_get_reference_value'
program.cpp:(.text._ZN4Napi11AsyncWorker4OnOKEv[_ZN4Napi11AsyncWorker4OnOKEv]+0xe8): undefined reference to `napi_call_function'
program.cpp:(.text._ZN4Napi11AsyncWorker4OnOKEv[_ZN4Napi11AsyncWorker4OnOKEv]+0x104): undefined reference to `napi_is_exception_pending'
program.cpp:(.text._ZN4Napi11AsyncWorker4OnOKEv[_ZN4Napi11AsyncWorker4OnOKEv]+0x126): undefined reference to `napi_get_reference_value'
program.cpp:(.text._ZN4Napi11AsyncWorker4OnOKEv[_ZN4Napi11AsyncWorker4OnOKEv]+0x13d): undefined reference to `napi_close_escapable_handle_scope'
program.cpp:(.text._ZN4Napi11AsyncWorker4OnOKEv[_ZN4Napi11AsyncWorker4OnOKEv]+0x18b): undefined reference to `napi_escape_handle'
CMakeFiles/program.dir/src/program.cpp.o: In function `Napi::Error::what() const':
program.cpp:(.text._ZNK4Napi5Error4whatEv[_ZNK4Napi5Error4whatEv]+0x42): undefined reference to `napi_open_escapable_handle_scope'
program.cpp:(.text._ZNK4Napi5Error4whatEv[_ZNK4Napi5Error4whatEv]+0x5f): undefined reference to `napi_get_reference_value'
program.cpp:(.text._ZNK4Napi5Error4whatEv[_ZNK4Napi5Error4whatEv]+0x81): undefined reference to `napi_get_named_property'
program.cpp:(.text._ZNK4Napi5Error4whatEv[_ZNK4Napi5Error4whatEv]+0xa2): undefined reference to `napi_escape_handle'
program.cpp:(.text._ZNK4Napi5Error4whatEv[_ZNK4Napi5Error4whatEv]+0xc1): undefined reference to `napi_close_escapable_handle_scope'
program.cpp:(.text._ZNK4Napi5Error4whatEv[_ZNK4Napi5Error4whatEv]+0xdd): undefined reference to `napi_get_value_string_utf8'
program.cpp:(.text._ZNK4Napi5Error4whatEv[_ZNK4Napi5Error4whatEv]+0x147): undefined reference to `napi_get_value_string_utf8'
CMakeFiles/program.dir/src/program.cpp.o: In function `Napi::AsyncWorker::OnWorkComplete(Napi::Env, napi_status)':
program.cpp:(.text._ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status[_ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status]+0x3b): undefined reference to `napi_open_handle_scope'
program.cpp:(.text._ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status[_ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status]+0x6c): undefined reference to `napi_create_string_utf8'
program.cpp:(.text._ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status[_ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status]+0x88): undefined reference to `napi_create_error'
program.cpp:(.text._ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status[_ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status]+0xff): undefined reference to `napi_create_reference'
program.cpp:(.text._ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status[_ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status]+0x142): undefined reference to `napi_get_reference_value'
program.cpp:(.text._ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status[_ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status]+0x172): undefined reference to `napi_get_reference_value'
program.cpp:(.text._ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status[_ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status]+0x19c): undefined reference to `napi_open_escapable_handle_scope'
program.cpp:(.text._ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status[_ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status]+0x1bf): undefined reference to `napi_get_reference_value'
program.cpp:(.text._ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status[_ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status]+0x1ed): undefined reference to `napi_call_function'
program.cpp:(.text._ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status[_ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status]+0x20c): undefined reference to `napi_is_exception_pending'
program.cpp:(.text._ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status[_ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status]+0x231): undefined reference to `napi_escape_handle'
program.cpp:(.text._ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status[_ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status]+0x24e): undefined reference to `napi_close_escapable_handle_scope'
program.cpp:(.text._ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status[_ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status]+0x2b3): undefined reference to `napi_close_handle_scope'
program.cpp:(.text._ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status[_ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status]+0x377): undefined reference to `napi_get_reference_value'
program.cpp:(.text._ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status[_ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status]+0x3a1): undefined reference to `napi_open_escapable_handle_scope'
program.cpp:(.text._ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status[_ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status]+0x3c4): undefined reference to `napi_get_reference_value'
program.cpp:(.text._ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status[_ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status]+0x3fc): undefined reference to `napi_call_function'
program.cpp:(.text._ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status[_ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status]+0x41b): undefined reference to `napi_is_exception_pending'
program.cpp:(.text._ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status[_ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status]+0x440): undefined reference to `napi_escape_handle'
program.cpp:(.text._ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status[_ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status]+0x45d): undefined reference to `napi_close_escapable_handle_scope'
program.cpp:(.text._ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status[_ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status]+0x491): undefined reference to `napi_delete_reference'
program.cpp:(.text._ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status[_ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status]+0x4c2): undefined reference to `napi_get_reference_value'
program.cpp:(.text._ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status[_ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status]+0x532): undefined reference to `napi_get_reference_value'
program.cpp:(.text._ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status[_ZN4Napi11AsyncWorker14OnWorkCompleteENS_3EnvE11napi_status]+0x778): undefined reference to `napi_delete_reference'
CMakeFiles/program.dir/src/program.cpp.o: In function `_register_mobilenetknn':
program.cpp:(.text.startup+0x6): undefined reference to `napi_module_register'
collect2: error: ld returned 1 exit status
CMakeFiles/program.dir/build.make:161: recipe for target 'program' failed
make[2]: *** [program] Error 1
CMakeFiles/Makefile2:110: recipe for target 'CMakeFiles/program.dir/all' failed
make[1]: *** [CMakeFiles/program.dir/all] Error 2
Makefile:90: recipe for target 'all' failed
make: *** [all] Error 2
ERR! OMG Process terminated: 2
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! demo@1.0.0 install: `cmake-js compile`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the demo@1.0.0 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
 
npm ERR! A complete log of this run can be found in:
npm ERR!     /home/nishant/.npm/_logs/2021-05-25T19_38_32_738Z-debug.log

CMakeLists.txt

cmake_minimum_required(VERSION 3.15)
project(mobilenetknn)
 
set(CMAKE_CXX_STANDARD 11)
 
SET(Caffe_DIR /home/nishant/caffe/distribute)
include_directories(${CMAKE_JS_INC})
include_directories(${Caffe_DIR}/include ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_SOURCE_DIR}/node_modules/node-addon-api)
 
file(GLOB_RECURSE SOURCE_O ${CMAKE_CURRENT_SOURCE_DIR}/lib/*.o GLOB SOURCE_FILES "src/*.cpp" "src/*.hpp")
# file(GLOB SOURCE_FILES "src/*.cpp" "src/*.hpp")
 
 
add_library(${PROJECT_NAME}
       STATIC ${SRC}
           ${SOURCE_O} ${CMAKE_JS_SRC})
 
# add_library(${PROJECT_NAME} SHARED ${SOURCE_FILES} ${CMAKE_JS_SRC})
# add_library(SHARED ${SOURCE_FILES} ${CMAKE_JS_SRC})
 
set_target_properties(${PROJECT_NAME} PROPERTIES PREFIX "" SUFFIX ".node")
 
add_definitions(-DCPU_ONLY)
target_link_libraries(${PROJECT_NAME} PRIVATE ${CMAKE_JS_LIB} ${Caffe_DIR}/lib/libcaffe.a)
 
SET(EXAMPLES
        program
)
# License source files
find_package(OpenMP)
if(OPENMP_FOUND)
   set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}")
   set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
endif()
find_package( OpenCV REQUIRED)
set(CMAKE_BUILD_TYPE release)
set(CMAKE_CXX_STANDARD 11)
 
add_definitions(-DCPU_ONLY)
 
find_package(HDF5 COMPONENTS HL REQUIRED)
include_directories(SYSTEM ${HDF5_INCLUDE_DIRS} ${HDF5_HL_INCLUDE_DIR})
list(APPEND Caffe_LINKER_LIBS ${HDF5_LIBRARIES})
list(APPEND Caffe_LINKER_LIBS ${HDF5_HL_LIBRARIES})
 
execute_process(COMMAND node -p "require('node-addon-api').include"
       WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
       OUTPUT_VARIABLE NODE_ADDON_API_DIR
       )
string(REPLACE "\n" "" NODE_ADDON_API_DIR ${NODE_ADDON_API_DIR})
string(REPLACE "\"" "" NODE_ADDON_API_DIR ${NODE_ADDON_API_DIR})
target_include_directories(${PROJECT_NAME} PRIVATE ${NODE_ADDON_API_DIR} ${CAMKE_JS_INC})
 
# target_include_directories(${PROJECT_NAME} PRIVATE "${CMAKE_SOURCE_DIR}/node_modules/node-addon-api")
# target_link_libraries(${PROJECT_NAME} PRIVATE ${CMAKE_JS_LIB})
add_definitions(-DNAPI_VERSION=3)
 
include_directories(${OpenCV_DIR}/include)
foreach (example ${EXAMPLES})
   add_executable(${example} src/${example}.cpp)
   TARGET_LINK_LIBRARIES(${example} ${OpenCV_LIBS} ${CMAKE_CURRENT_LIST_DIR}/build/libmobilenetknn.a ${HDF5_LIBRARIES} ${HDF5_HL_LIBRARIES} -lopenblas -lprotobuf -lboost_system -lglog -lgflags -lopencv_core -lopencv_highgui -lopencv_imgproc -lopencv_ml -lopencv_imgcodecs -lopencv_videoio  -lboost_system -lboost_regex -lboost_filesystem -lboost_thread -lboost_log)
endforeach()

main file(program.cpp) I commented some of the functions, the same problem was with other functions also.

#include <opencv2/core/core.hpp>    
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/ml.hpp>
 
#include <iostream>
#include <stdio.h>
#include <string>
#include <vector>
// #include "napi.h"
#include <napi.h>
// #include <node_modules/node-addon-api/napi.h>
 
using namespace std;
using namespace cv;
using namespace cv::ml;
// using namespace Napi;
 
struct classInfo{
  int classid;
  std::string classname;
  std::string imageset_location;
};
 
class Classify{ // declaration of class classify
public:
   Classify(); //constructor
   ~Classify(); //destructor
 
       std::vector<classInfo>cls;
   int counter=0;
   Ptr<KNearest> trainedModel;
 
   std::string infer(std::string data_path);
   void loadModel(string knn_path="train.knn");
   std::string exportTrainedModel();
   void trainModel(vector<classInfo>cls);
   void listClasses(vector<classInfo>n);
   vector<classInfo> addClass(std::string classname, std::string imageset_location);
 
 
};
 
Classify ic;
 
Napi::Number classAddTrainModel(const Napi::CallbackInfo& info){
   Napi::Env env = info.Env();
 
   // number of classes
   int n = info[0].ToNumber();
   Napi::Array classn = info[1].As<Napi::Array>();
   Napi::Array iloc = info[2].As<Napi::Array>();
   vector<classInfo> classinfo;
 
   for(int i  = 0; i < n; i++){
       Napi::Value x = classn[i];
       Napi::Value y = iloc[i];
       string className = (string)x.As<Napi::String>();
       string loc = (string)y.As<Napi::String>();
       // cout << className << endl << loc << endl;
       classinfo = ic.addClass(className, loc);       
   }
 
   // Train Model
   ic.trainModel(classinfo);
 
   return Napi::Number::New(env, 1);
}
 
// Napi::String modelExport(const Napi::CallbackInfo& info){
//     Napi::Env env = info.Env();
  
//     std::string path = ic.exportTrainedModel();
//     return Napi::String::New(env, ic.exportTrainedModel());
// }
 
// Napi::String modelLoad(const Napi::CallbackInfo& info){
//     Napi::Env env = info.Env();
 
//     std::string modelPath = info[0].ToString();
//     std::string imgPath = info[1].ToString();
 
//     ic.loadModel(modelPath);
//     std::string label = ic.infer(imgPath);
  
//     return Napi::String::New(env, label);
// }
 
Napi::Object Init(Napi::Env env, Napi::Object exports){
   // set a key on exports object
   exports.Set(
       Napi::String::New(env, "classAddTrainModel"),
       Napi::Function::New(env, classAddTrainModel)
   );
   // exports.Set(
   //     Napi::String::New(env, "modelExport"),
   //     Napi::Function::New(env, modelExport)
   // );
   // exports.Set(
   //     Napi::String::New(env, "modelLoad"),
   //     Napi::Function::New(env, modelLoad)
   // );
  
   // return 'exports' object (always)
   return exports;
}
 
// register 'greet' module which calls Init method
NODE_API_MODULE(mobilenetknn, Init);
 
int main(){
   return 0;
}