question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
69,456,325
69,456,691
i am looking for the right answer for this question, is this correct?
Write a function void switchEnds(int *array, int size); that is passed the address of the beginning of an array and the size of the array. The function swaps the values in the first and last entries of the array. #include <iostream> using namespace std; void switchEnd(int *array, int size){ int temp=array[0]; array[0]=array[size-1]; array[size-1]=temp; } int main() { const int size=5; int array[size]={1,2,3,4,5}; switchEnd(array,size); for (int c=0;c<5;c++) cout<<array[c]<<" "; }
There are multiple ways to do this. Your way is the straight forward way. But the question reminds me of some questions of c++ courses, where you should understand pointers. If this is the case, then an answer like this might be better: void switchEnd(int *start, int size){ int *end = start + size - 1; int temp=*start *start = *end *end = temp } Be aware that this solution is not the nice way. It is hard to understand and unhandy. So if you want to implement something like this somewhere in your code, use your solution. Or better: void switchEnd(int *array, int size){ std::swap(array[0], array[size-1]); }
69,456,736
69,461,671
Read zst compressed pcap with libpcap
I would like to decode zst and gz pcap with libpcap but I am not able to find any example doing so. Of course I don't want to have a temporary decompressed pcap file. Could you guys point me to the right methods ? Thanks
Libpcap doesn't currently support reading compressed files. If you don't want to have a temporary decompressed pcap file, the only way to do so would be to have your program create a pipe, run another program that reads the compressed file and writes the decompressed file data to the standard output with its standard output being the write side of the pipe, make a standard I/O stream from the read side of the pipe (using, for example, fdopen() on a Unix-like system), and then use pcap_fopen_offline() to open that standard I/O stream as a capture file. That way, the other program will do the decompression, but will write it to a pipe rather than to a file, and your program will read the decompressed data from the pipe.
69,456,917
69,457,380
Should I always define a constexpr static data member outside of the class?
Why a constexpr static data member needs to be defined outside of the class on C++11, C++14 but it doesn't need that requirement on c++ 17, 20 and above? struct Array{ int static constexpr sz_ = 5; int ar_[sz_]{}; }; //int constexpr Array::sz_; // needed on `C++11`, `C++14` but not needed for C++17, C++20 void foo(int const& x){ } int main(){ foo(Array::sz_); } So is this a change in the standard? or should I always define that member outside of the class?
Should I always define a constexpr static data member outside of the class? Always?! Only a Sith deals in absolutes. C++17 made static constexpr variables implicitly inline (in the linkage sense, they always needed an in-class initializer). The out-of-class definition remains an optional but deprecated feature. D.1 Redeclaration of static constexpr data members [depr.static_constexpr] 1 For compatibility with prior C++ International Standards, a constexpr static data member may be redundantly redeclared outside the class with no initializer. This usage is deprecated. [ Example: struct A { static constexpr int n = 5; // definition (declaration in C++ 2014) }; constexpr int A::n; // redundant declaration (definition in C++ 2014)  — end example ] It's still supported, so you don't have to go about updating all of your existing code bases today. But it may be removed in the future (three, six, maybe nine years from now?) So you won't be able to add a redundant declaration forever. If you write a new piece of code that requires C++17 or newer, then there's no need to add this re-declaration out of some principle.
69,457,205
69,457,235
How to pass object array to a function?
class department { void max() ***HOW TO PASS ARRAY OF OBJECT HERE , WHAT PARAMETERS SHOULD I PASS*** { } }; class B : public department { }; int main() { B a[10]; // a.max(a,n); ***HOW TO CALL THIS max FUNCTION*** return 0; } I want to pass the array of object a[10] to the max function. How do I call it and pass it? I don't want to do it like this: for(i = 0; i < n; i++) { a[i].max }
You implemented max() as a non-static method of department, so you need a department object to call it on, like each B object in your array, eg: for(int i = 0; i < 10; ++i) { a[i].max(); } If this is not what you want, then max() needs to be taken out of department, or at least made to be static instead. Either way, you will have to change its input parameters to accept the array. Try something more like this instead: class department { public: static void max(department *depts, int count) { //... } }; class B : public department { }; int main() { B a[10]; department::max(a, 10); return 0; } Online Demo Alternatively: class department { }; class B : public department { }; void max(department *depts, int count) { //... } int main() { B a[10]; max(a, 10); return 0; } Online Demo
69,457,893
69,457,996
Problem receiving an array as pointer parameter
Hi I have a trouble trying to manage a the following array. I have initialized this pointer int* coordenadasFicha = new int[2]; and I want to asign the two int asking the user for the numbers. The trouble appears when I call pedirCoordenadasFicha(coordenadasFicha); Clion recomends me cast coordenadasFicha to int** but I need to use it as a simple pointer. pedirCoordenadasFicha() basically does this: void pedirCoordenadasFicha(int* coordenadasFicha[2]){ std::cin >> *coordenadasFicha[0]; std::cin >> *coordenadasFicha[1];} All help is welcome
An int* (a pointer-to-int) and an int*[] (an array of pointer-to-int) are two different things. And actually, in a function parameter, int* coordenadasFicha[2] is actually passed as int** (pointer to pointer-to-int), because an array decays into a pointer to its 1st element. In your case, you are creating coordenadasFicha as an dynamic array of ints, but your function is expecting an array of int* pointers instead. So, to do what you are attempting, you would need to do either this: void pedirCoordenadasFicha(int* coordenadasFicha){ std::cin >> coordenadasFicha[0]; std::cin >> coordenadasFicha[1]; } int* coordenadasFicha = new int[2]; pedirCoordenadasFicha(coordenadasFicha); ... delete[] coordenadasFicha; Or this: void pedirCoordenadasFicha(int* coordenadasFicha[2]){ std::cin >> *coordenadasFicha[0]; std::cin >> *coordenadasFicha[1]; } int** coordenadasFicha = new int*[2]; for(int i = 0; i < 2; ++i) { coordenadasFicha[i] = new int; } pedirCoordenadasFicha(coordenadasFicha); ... for(int i = 0; i < 2; ++i) { delete coordenadasFicha; } delete[] coordenadasFicha; Or, just get rid of new altogether, and pass the array by reference: void pedirCoordenadasFicha(int (&coordenadasFicha)[2]){ std::cin >> coordenadasFicha[0]; std::cin >> coordenadasFicha[1]; } int coordenadasFicha[2]; pedirCoordenadasFicha(coordenadasFicha); ...
69,458,100
69,469,262
Boost log working on W10 but not in ubuntu - segmentation fault
After testing the Boost.log on W10 with Visual Studio 2019, I am trying to have the same application (writes a simple log file) running in ubuntu using the Windows Subsystem for Linux. So, I created a new project with the same source files, configured it to build on WSL using GCC, and indicated to the Linker the boost libraries to look for on WSL. At first, I was getting a lot of linking errors such as "undefined reference to boost::log::v2s_mt_posix..." which disappeared after adding #define BOOST_LOG_DYN_LINK 1 as suggested here: linker error while linking boost log tutorial (undefined references) With this I was able to start debugging with VS but eventually I get a "segmentation fault" when calling logging::add_common_attributes() in this function void LOG_InitLogging() { logging::register_simple_formatter_factory<logging::trivial::severity_level, char>( "Severity" ); logging::add_file_log( keywords::file_name = "s.log", //output file keywords::format = "[%TimeStamp%] [%LineID%] [%ThreadID%] [%ProcessID%] [%Severity%] ", keywords::auto_flush = true ); logging::add_common_attributes(); } I am not very familiar with linux or linking against libraries so some guidance would be greatly appreciated. Thank you!
In the VS project, despite correctly indicating the linker (Configuration Properties => Linker => Input => Additional dependencies) to look for boost libraries on WSL, I was also including (Configuration Properties => C/C++ => General => Additional Include directories) the path to the boost headers that are on my Windows system, so IntelliSense would not show those red underlines (I've read somewhere I could do it for that purpose). After removing the path to the Windows boost headers, the segmentation fault did not happen ever again.
69,458,205
69,458,238
Execvp not executing ping command with arguments
I am using the exevcp system call in order to execute "ping www.google.com". However, when I execute the code below: #include <iostream> #include <vector> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> using namespace std; int main(int argc, char *argv[]){ vector<char*> pingArgs; pingArgs.push_back("www.google.com"); pingArgs.push_back(NULL); execvp("ping", &pingArgs[0]); return 0; } The below output is displayed, implying that I did not provide a link as an argument to the ping command. This seems strange, considering that in the vector which stores the arguments, I clearly added "www.google.com": Usage: ping [-aAbBdDfhLnOqrRUvV64] [-c count] [-i interval] [-I interface] [-m mark] [-M pmtudisc_option] [-l preload] [-p pattern] [-Q tos] [-s packetsize] [-S sndbuf] [-t ttl] [-T timestamp_option] [-w deadline] [-W timeout] [hop1 ...] destination Usage: ping -6 [-aAbBdDfhLnOqrRUvV] [-c count] [-i interval] [-I interface] [-l preload] [-m mark] [-M pmtudisc_option] [-N nodeinfo_option] [-p pattern] [-Q tclass] [-s packetsize] [-S sndbuf] [-t ttl] [-T timestamp_option] [-w deadline] [-W timeout] destination
vector<char*> pingArgs; pingArgs.push_back("www.google.com"); pingArgs.push_back(NULL); The first parameter to a program, it's argv[0], is the name of the program itself. Here, you're merely informing the ping program that it's name is www.google.com, and it has no additional parameters. vector<char*> pingArgs; pingArgs.push_back("ping"); pingArgs.push_back("www.google.com"); pingArgs.push_back(NULL); The first parameter to execvp is the executable to execute, but you still must provide all parameters separately. However, all of the above is completely wrong anyway, for a tangential reason. In modern C++ string literals are const char *, and not char *. You must be using an ancient C++ compiler that either relaxes const-correctness when it comes to string literals or fails to implement it correctly, and I expect every modern C++ compiler to fail to compile the shown code for this unrelated reason. Correctly doing this requires a little bit more work, in C++, but that's not directly related to the question you asked, and would be a separate question.
69,458,260
69,471,588
CMakelist include subfolders
I can't figure out how to import my source files, which are in a different directory. The structure of my project looks like this: root - src - core App.h App.cpp CMakelist.txt CMakelist.txt main.cpp CMakelist.txt My main CMakelist under root looks like this: cmake_minimum_required(VERSION 3.17) project(edu) set(CMAKE_CXX_STANDARD 17) ## add subdirectory with source files add_subdirectory(src) add_executable(edu main.cpp) My CMakelist under src looks like this: add_subdirectory(core) And finaly my CMakelist under core looks like this: set(all_src App.h App.cpp ) target_sources(core ${all_src}) But it doesn't work, I get an error: Cannot specify sources for target "core" which is not built by this project How do I fix it? My project is getting quite large and it would be convenient to put all the files in different directories instead of stacking them in add_executable Thx!
If you do not want to use a separate library for core, you can use the following structure in src/CMakeLists.txt: # core sources set(core_srcs core/App.cpp core/App.h) # aux sources set(aux_srcs aux/stuff.cpp aux/stuff.h) add_executable(edu main.cpp ${core_srcs} ${aux_srcs}) This lets you organize your CMakeLists.txt by module and keep your sources in different directories, without exploding the number of CMakeLists and sublibraries.
69,458,664
69,470,606
uWebsocket sending messages via WebSocket outside of the .message Behavior context
I have to open with the obligatory, I'm pretty trash at c++, fresh out of college. I setup uWebsocket as a server, it's currently just echoing responses back to the client. I am trying to setup a queue on a separate thread that can respond to the client at times OTHER than when I recieve a message. I'm killing myself over here though because I cannot find the appropriate type for a function outside of the context of the main thread. void RelaySocket(){ struct SocketData{ //Empty because we don't need any currently. }; uWS::App() .listen(8766, [](auto *listen_socket){ if(listen_socket){ std::cout<< "Listening on port" << 8766<< std::endl; }; }) .ws<SocketData>("/*",uWS::TemplatedApp<false>::WebSocketBehavior<SocketData> {//I have to explicitly declare the type of this struct. .open = [](auto *ws){ std::cout<< "test"<< std::endl; }, .message = [](auto *ws, std::string_view message, uWS::OpCode opCode){ //The docs show how to send messages from this context, but no other method is demonstrated. ws->send("My message");// This works fine enough. //What I'm trying to do. outerFunction(ws); } }).run(); } void outerFunction([Unknown Type] *ws){// I have NO idea what type would play nice in this spot. I've tried uWS::Websocket<false>, and others to no avail. //Processes information before replying ... //sends n amount of reply's. ws->send("sick Data.");//the outcome I'm looking for. } I've tried using the Type_def feature, and it still isn't playing nice. std::cout << typeid(ws).name() << std::endl; returned PN3uWS9WebSocketILb0ELb1EZ11RelaySocketvE10SocketDataEE My first post, so my bad if I didn't post all applicable information. EDIT: . the code below worked for me. Thanks again. struct SocketData{ //Empty because we don't need any currently. }; void SocketResponse(uWS::WebSocket<false,true,SocketData> *ws ){ ws->send("test"); std::cout<< "test"<<std::endl; };
From the uWebsocket docs, the type of ws is: WebSocket<SSL, true, int> * Thus, you can try to use the following. Note: You probably need to forward-declare outerFunction as well. void outerFunction(uWS::WebSocket<SSL, true, int> *ws); void RelaySocket(){ struct SocketData{ //Empty because we don't need any currently. }; uWS::App() .listen(8766, [](auto *listen_socket){ if(listen_socket){ std::cout<< "Listening on port" << 8766<< std::endl; }; }) .ws<SocketData>("/*",uWS::TemplatedApp<false>::WebSocketBehavior<SocketData> {//I have to explicitly declare the type of this struct. .open = [](auto *ws){ std::cout<< "test"<< std::endl; }, .message = [](auto *ws, std::string_view message, uWS::OpCode opCode){ //The docs show how to send messages from this context, but no other method is demonstrated. ws->send("My message");// This works fine enough. //What I'm trying to do. outerFunction(ws); } }).run(); } void outerFunction(uWS::WebSocket<SSL, true, int> *ws){// I have NO idea what type would play nice in this spot. I've tried uWS::Websocket<false>, and others to no avail. //Processes information before replying ... //sends n amount of reply's. ws->send("sick Data.");//the outcome I'm looking for. } int main() { RelaySocket(); return 0; } Also, the uWS::Websocket is from WebSocket.h: template <bool SSL, bool isServer, typename USERDATA> struct WebSocket : AsyncSocket<SSL> { template <bool> friend struct TemplatedApp; template <bool> friend struct HttpResponse; private: typedef AsyncSocket<SSL> Super; void *init(bool perMessageDeflate, CompressOptions compressOptions, BackPressure &&backpressure) { new (us_socket_ext(SSL, (us_socket_t *) this)) WebSocketData(perMessageDeflate, compressOptions, std::move(backpressure)); return this; } }
69,458,957
69,458,995
Parametrized custom stream manipulators - why overload "operator<<"?
I am trying to implement a parametrized stream manipulator for a certain set of data. I do it the simple way as recommended: class print_my_data { private: . . . public: print_my_data(. . .) { . . . } ostream& operator()(std::ostream& out) { return out << . . . << endl; } }; ostream& operator<<(ostream& out, print_my_data md) // <=== MY QUESTION BELOW IS ABOUT THIS { return md(out); } Usage: clog << print_my_data(. . .) << endl; This works fine; but I really don't understand why it doesn't work unless I define operator<<! Why won't it call the same overloaded function as it does for endl?? (i.e. as an object that can be applied to the stream through operator())
The overload you're looking for is only defined for function pointers. basic_ostream& operator<<( std::basic_ostream<CharT,Traits>& (*func)(std::basic_ostream<CharT,Traits>&) ); Your print_my_data class is a callable object (a functor, in C++ terms). But it is not a function pointer. On the other hand, endl is a function, and hence has a function pointer (in fact, it's one of the few functions in the C++ standard library which do have an address) A not-unreasonable argument could be made that the overload should look like basic_ostream& operator<<( std::function<std::basic_ostream<CharT,Traits>&(std::basic_ostream<CharT,Traits>&)> func); But alas, std::function wasn't around when the I/O manipulation operators were written. Neither were concepts, for that matter. And using SFINAE to declare template <typename F> basic_ostream& operator<<( F func); would have just opened an entire Pandora's box worth of messy details that the standards committee didn't want to deal with.
69,459,016
69,460,933
How can I calculate the complexity of a program like this
So I have been studying the complexity of algorithms, but this one I can't uderstand. If I use a global variable to check how many times the function is called it will calculate the number 11 then saying that the complexity is O(2*N), but when looking at the problem I thought the complexity would be O(N). #include <cstdlib> #include <iostream> using namespace std; class node { public: int data; node* left; node* right; node(int data){ this->data = data; this->left = NULL; this->right = NULL; } }; int funcUtil(node* node, int min, int max) { cout << "a"; if (node==NULL) return 1; if (node->data < min || node->data > max) return 0; return funcUtil(node->left, min, node->data-1) && funcUtil(node->right, node->data+1, max); } int func(node* node) { return(funcUtil(node, INT_MIN, INT_MAX)); } int main() { node *root = new node(4); root->left = new node(2); root->right = new node(5); root->left->left = new node(1); root->left->right = new node(3); if(func(root)) cout<<"YES"; else cout<<"NO"; return 0; }
Big O notation works like this: O(c * f(x)) = O(f(x)), c!=0 In other words, you can always multiply the function inside the parenthesis by an arbitrary non-zero real constant. So O(2N) = O(N) Another property of big O notation is that you can omit lower order terms: O(x^2 + x) = O(x^2) O(a^x + p(x)) = O(a^x) where a>1 and p(x) is a polynomial of x Further reading: https://en.wikipedia.org/wiki/Big_O_notation
69,459,984
69,461,975
c++11 way of returning an array of unknown number of elements
I would like to implement this function (or a similar one, see the requirements below) in C++11: template<typename... ARGS> constexpr std::array<const typename std::common_type<ARGS...>::type, sizeof...(ARGS)> asConstArray(ARGS&&... args) { return {std::forward<ARGS>(args)...}; } struct DataBinding { static constexpr auto getRawBindings() // HERE ^- C++14, deduced to std::array<const BindingInfo, 2> in this case { return asConstArray( DEF_BINDING(int, stateProp, stateParam), //BindingInfo constexpr object DEF_BINDING(float, areaProp, areaParam) //BindingInfo constexpr object //(...) ); } }; As you see I would like to introduce a macro-based interface (it is necessary, it does a lot of other Qt related magic). DEF_BINDING returns a constexpr object of an user-defined struct (BindingInfo - it contains a few const char* and size_t members, it can be replaced with any struct or template that can contain the same). I don't want to force the programmer to count the bindings manually because it would be inconvenient. The solution above is the closest I could figure out, but I would like to solve the followings in C++11: Needs to return an array of elements (array like, using std::array is not a must-have) Must be compile time The items must be defined only once (do not want to enumerate the array elements twice) Must be header-only (static constexpr member defined in the cpp file cannot work, non-ODR regulated use can work) The array-size must be auto-deduced The solution can use any kind of C++11 magic. I hope we can figure out something :) UPDATE: In the original post I forgot to mention a really important fact: getRawBindings is inside a struct.
Trailing return type should do the job: struct DataBinding { static constexpr auto getRawBindings() -> decltype( asConstArray( DEF_BINDING(int, stateProp, stateParam), //BindingInfo constexpr object DEF_BINDING(float, areaProp, areaParam) //BindingInfo constexpr object //(...) ) ) { return asConstArray( DEF_BINDING(int, stateProp, stateParam), //BindingInfo constexpr object DEF_BINDING(float, areaProp, areaParam) //BindingInfo constexpr object //(...) ); } }; To avoid the repetition, MACRO might help: #define RETURN(Expr) decltype(Expr) { return Expr; } and then struct DataBinding { static constexpr auto getRawBindings() -> RETURN( asConstArray( DEF_BINDING(int, stateProp, stateParam), //BindingInfo constexpr object DEF_BINDING(float, areaProp, areaParam) //BindingInfo constexpr object //(...) ) ) };
69,460,287
69,697,203
std::fstream file not getting created while making a custom Csv file manager class
I'm a beginner to C++. I made a simple program which collects information of cars and stores it into classes. This was just for the purpose of learning more about classes. I wanted to store the data of cars to a csv file. But it is very complicated so I tried to make a class called CSVFile to manage csv files. But I cant even get the constructors to work. I don't get any error, but when i make an object it doesn't create the file. #include <iostream> #include <vector> #include <string> #include <fstream> class CSVFile { public: CSVFile(std::string _name): name(_name) { file.open(name); } private: std::ifstream file; std::string name; }; int main() { CSVFile myFile("my.csv"); return 0; }
The file opened successfully when I opened it with std::fstream::app append mode.
69,460,318
69,460,341
What is Foo(int* ptr): ptr_{ptr}{}?
I saw this code in the book "C++ High Performance" by Bjorn Andrist and Viktor Sehr. The code example is actually used to show the point that "Compiles despite function being declared const!", and I am aware of this. However, I have not seen int* ptr_{}; and Foo(int* ptr):ptr_{ptr}{} before this point. What are these two pieces of code doing, especifically Foo(int* ptr):ptr_{ptr}{}? The entire code snippet used as an example was this: class Foo { public: Foo(int* ptr):ptr_{ptr}{} auto set_ptr_val(int v) const { *ptr_ = v; // Compiles despite function being declared const! } private: int* ptr_{}; }; int main(){ auto i = 0; const auto foo = Foo{&i}; foo.set_ptr_val(42); }
Foo(int* ptr) : ptr_{ptr}{} Declares and defines a constructor for the class Foo, which takes in input a int * (pointer to int), and initializes the member variable ptr_ via the member initializer list; it does nothing more, so the body is emtpy, {}. int* ptr_{}; uses one possible syntax of value initialization to zero initialize ptr_; since it of type int*, it will be inialized with nullptr, so that's equivalent to int* ptr_{nullptr};. As regards the point they're making, I think they are overstressing a normal observation thus making it look like a special rule: the class has a member named ptr_ which is a int*, i.e. a pointer to int; the member function set_ptr_val is const, so it makes the promise that it won't change ptr_ or any other (non-mutable) member; indeed set_ptr_val's body doesn't modify ptr_; what it modifies is the pointed-to int. But that's ok.
69,460,680
69,461,413
i was not declear in thiscscope cpp,but another i is working Q:ARRAY OF OBJECT
` SHOWING i IS NOT DECLEARED IN THIS SCOPE question: of ARRAY OF OBJECT. #include<iostream> using namespace std; class employee{ char name[30]; float age; public: void getdata(); void putdata(); }; void employee::getdata() { cout<<"Enter name"<<endl; cin>>name; cout<<"Enter the age "<<endl; cin>>age; } void employee :: putdata() { cout<<"Name "<<name<<endl; cout<<"age "<<age<<endl; } const int size=3; int main() { employee manager[size]; for(int i=0;i<size;i++) { cout<<"manager details"<<i+1<<endl; manager[i].getdata(); } cout<<endl; { for(int i=0;i<size;i++) cout<<"manager details"<<i+1<<endl; manager[i].putdata();//main problem is here } return 0 ; }` here the link of error msg https://cpphelp4-u.blogspot.com/2021/10/array-of-object-error-msg-picture-link.html
#include<iostream> using namespace std; class employee{ char name[30]; float age; public: void getdata(); void putdata(); }; void employee::getdata() { cout<<"Enter name"<<endl; cin>>name; cout<<"Enter the age "<<endl; cin>>age; } void employee :: putdata() { cout<<"Name "<<name<<endl; cout<<"age "<<age<<endl; } const int size=3; int main() { employee manager[size];//size? for(int i=0;i<size;i++) { cout<<"manager details"<<i+1<<endl;//i+1?? manager[i].getdata();//i? } cout<<endl; for(int i=0;i<size;i++) { //PROBLEM WAS HERE , cout<<"manager details"<<i+1<<endl; manager[i].putdata(); } return 0 ; }
69,460,697
69,862,803
Program 'test.exe' failed to run: Access is denied vs code C error
this is the error message Program 'test.exe' failed to run: Access is deniedAt line:1 char:91 + ... cuments\arpit\" ; if ($?) { gcc test.c -o test } ; if ($?) { .\test } + ~~~~~~. At line:1 char:91 + ... cuments\arpit\" ; if ($?) { gcc test.c -o test } ; if ($?) { .\test } + ~~~~~~ + CategoryInfo : ResourceUnavailable: (:) [], ApplicationFailedException + FullyQualifiedErrorId : NativeCommandFailed this is the error i have been getting on my VS code .. i have installed the latest version of Min GW and also all the extention required .. i have not been able to find out the solution please help... P.S i am able to run C++ programs without any issues but not the C programs
I had the same error just a few minutes ago, but I found the solution. It is because your Antivirus program 'erases?' the exe files so they can't run. If you are using Avast, you should turn off hardened mode (stopped working after I turned it on). This is the video where I found the solution. It works for me just fine: https://www.youtube.com/watch?v=oMOjIjGYjcA
69,461,396
69,461,531
How to make a function that accepts another one with argument tuple
I need a function My_func that works like this auto f = [](const std::tuple<string, double>& t) { return std::get<0>(t); }; assert(My_func(f)("Hello", 8.5) == f({"Hello", 8.5})); Now i have template <class F> constexpr auto My_func(F&& f) { return [f](auto&& args...) { return std::forward<F>(f)(args); }; } But it doesn't work.What should i fix?
template <class F> constexpr auto My_func(F&& f) { return [f = std::forward<F>(f)](auto&&... args) { return f(std::make_tuple(std::forward<decltype(args)>(args)...)); }; }
69,461,415
69,461,683
Function default argument value depending on argument name in C++
If one defines a new variable in C++, then the name of the variable can be used in the initialization expression, for example: int x = sizeof(x); And what about default value of a function argument? Is it allowed there to reference the argument by its name? For example: void f(int y = sizeof(y)) {} This function is accepted in Clang, but rejected in GCC with the error: 'y' was not declared in this scope Demo: https://gcc.godbolt.org/z/YsvYnhjTb Which compiler is right here?
According to the C++17 standard (11.3.6 Default arguments) 9 A default argument is evaluated each time the function is called with no argument for the corresponding parameter. A parameter shall not appear as a potentially-evaluated expression in a default argument. Parameters of a function declared before a default argument are in scope and can hide namespace and class member name It provides the following example: int h(int a, int b = sizeof(a)); // OK, unevaluated operand So, this function declaration void f(int y = sizeof(y)) {} is correct because, in this expression sizeof(y), y is not an evaluated operand, based on C++17 8.3.3 Sizeof: 1 The sizeof operator yields the number of bytes in the object representation of its operand. The operand is either an expression, which is an unevaluated operand (Clause 8), or a parenthesized type-id. and C++17 6.3.2 Point of declaration: 1 The point of declaration for a name is immediately after its complete declarator (Clause 11) and before its initializer (if any), except as noted below.
69,461,735
69,462,436
Is it possible to store a type in C++?
Is there any easy way to keep the type of variable? For example storing in general container std::map<key, std::any> myMap; will cast values types to std::any, and init types will be forgotten. If only somehow to store type as a std::string, and then compare it with typeid(someType).name(). But it seems realy inconvenient to restore types in such manner. It seems pretty useful to have some functional of storing type by itself: type my_type = int; // or any other type my_type data = ...; std::map<key, std::pair<type, std::any>> myMap;
If you just need to check if the current type of the stored value in an std::any is a certain type, you could use std::any::type(): #include <any> #include <cassert> #include <typeinfo> int main() { std::any foo; assert(foo.type() == typeid(void)); foo = 1; assert(foo.type() == typeid(int)); foo = 1.23; assert(foo.type() == typeid(double)); }
69,462,332
69,462,566
Receive variadic sized raw arrays of the same type in a C++ template function
I would like to implement the following logic, I'm not sure if it is possible: #include <stddef.h> #include <array> template<size_t SIZE> constexpr std::array<const char*, 1> fun(const char (&name)[SIZE]) { return {name}; } template<size_t SIZE_1, size_t SIZE_2> constexpr std::array<const char*, 2> fun(const char (&name1)[SIZE_1], const char (&name2)[SIZE_2]) { return {name1, name2}; } // I would like to do something like this: template<size_t... SIZES> constexpr std::array<const char*, sizeof...(SIZES)> fun(const char (&/*???*/)[SIZES]/*...*/) { //??? } int main() { static constexpr auto fun1 = fun("aaa"); static constexpr auto fun2 = fun("aaa", "bbb"); //static constexpr auto funN = fun("aaa", "bbb", "ccc"); } It is important to get the parameters as raw arrays to do additional compile time magic on them.
Knowing where to put the ... is much simpler with a type alias template<std::size_t N> using chars = const char (&)[N]; template<std::size_t... SIZES> constexpr std::array<const char*, sizeof...(SIZES)> fun(chars<SIZES>... names) { return { names... }; } See it on coliru
69,462,409
69,478,510
int8 parameter input for imgSessionSaveBufferEx()
I am trying to execute the imgSessionSaveBufferEx function: I would like to save an image into PNG format, what should I input as the parameter for Int8* file_name? imgSessionSaveBufferEx(sessionID, NULL, ______);
The sequence of attempts are below: imgSessionSaveBufferEx(sessionID, NULL, "test.png"); imgSessionSaveBufferEx(sessionID, NULL, reinterpret_cast<Int8*>("test.png")); // this is the answer, provided by Botje imgSessionSaveBufferEx(sessionID, NULL, reinterpret_cast<Int8*>(const_cast<char *>("test.png")));
69,463,047
69,463,162
how to print template typename in c++?
I am writing a wrapper for boost numeric_cast with the wrapper function something like: #include <boost/numeric/conversion/cast.hpp> #include <stdexcept> template <typename Source, typename Target> Target numeric_cast(Source src) { try { // calling boost numeric_cast here } catch(boost::numeric::bad_numeric_cast& e) { throw std::runtime_error("numeric_cast failed, fromType: " + Source + " toType: " + Target); } } I am having this error: error: expected primary-expression before ‘(’ token throw std::runtime_error("numeric_cast failed ... ^ I think the error is asking to handle Source and Target in the error message. So is there a way to print template typename? I am a beginner in c++, so it maybe a silly question...
You can use typeid(T).name() to get the raw string of the template parameter: #include <boost/numeric/conversion/cast.hpp> #include <stdexcept> #include <typeinfo> template <typename Source, typename Target> Target numeric_cast(Source src) { try { // calling boost numeric_cast here } catch(boost::numeric::bad_numeric_cast& e) { throw (std::string("numeric_cast failed, fromType: ") + typeid(Source).name() + " toType: " + typeid(Target).name()); } } Demo. Please note that the string literal "numeric_cast failed, fromType:" should be std::string type to support '+' operator.
69,463,504
69,463,748
C++ Array function pointer with class
Below is my class code : enum style{BASIC, WEATHER_ONLY}; enum area{AREA0, AREA1, AREA2, AREA3, AREA4, AREA5, NULL_AREA}; enum display{NTP_TIME, TWO_DAY_WEATHER, TREE_DAY_WEATHER, WEEK_WEATHER, TEMPERATURE_AND_HUMIDITY}; typedef struct areaFormat { unsigned int x0; unsigned int y0; unsigned int width; unsigned int height; unsigned int nextSpace; }AreaFormat; class DisplayTemplate { public: void NTPTime(AreaFormat range); void TwoDayWeather(AreaFormat range); void TreeDayWeather(AreaFormat range); void WeekWeather(AreaFormat range); void TemperatureAndHumidity(AreaFormat range); typedef struct setting { AreaFormat areaParameter; void (DisplayTemplate::*function)(AreaFormat); }BlockParameter; void (DisplayTemplate::*Display[7])(AreaFormat) = {&DisplayTemplate::NTPTime, &DisplayTemplate::TwoDayWeather, &DisplayTemplate::TreeDayWeather, &DisplayTemplate::WeekWeather, &DisplayTemplate::TemperatureAndHumidity}; BlockParameter displayStyle[TEMPLATE_MAX_STYLE][DISPLAY_MAX_BLOCK] = { { {.areaParameter ={.x0=0, .y0=0, .width=0, .height=0, .nextSpace=AREA2}, .function=Display[NTP_TIME]}, {.areaParameter ={.x0=0, .y0=0, .width=0, .height=0, .nextSpace=NULL_AREA}, .function=Display[TWO_DAY_WEATHER]}, {.areaParameter ={.x0=0, .y0=0, .width=0, .height=0, .nextSpace=AREA3}, .function=Display[TREE_DAY_WEATHER]}, {.areaParameter ={.x0=0, .y0=0, .width=0, .height=0, .nextSpace=NULL_AREA}, .function=Display[WEEK_WEATHER]}, {.areaParameter ={.x0=0, .y0=0, .width=0, .height=0, .nextSpace=NULL_AREA}, .function=Display[TEMPERATURE_AND_HUMIDITY]}, {.areaParameter ={.x0=0, .y0=0, .width=0, .height=0, .nextSpace=NULL_AREA}, .function=Display[NTP_TIME]} }, { {.areaParameter ={.x0=0, .y0=0, .width=0, .height=0, .nextSpace=AREA2}, .function=Display[NTP_TIME]}, {.areaParameter ={.x0=0, .y0=0, .width=0, .height=0, .nextSpace=NULL_AREA}, .function=Display[TWO_DAY_WEATHER]}, {.areaParameter ={.x0=0, .y0=0, .width=0, .height=0, .nextSpace=AREA3}, .function=Display[TREE_DAY_WEATHER]}, {.areaParameter ={.x0=0, .y0=0, .width=0, .height=0, .nextSpace=NULL_AREA}, .function=Display[WEEK_WEATHER]}, {.areaParameter ={.x0=0, .y0=0, .width=0, .height=0, .nextSpace=NULL_AREA}, .function=Display[TEMPERATURE_AND_HUMIDITY]}, {.areaParameter ={.x0=0, .y0=0, .width=0, .height=0, .nextSpace=NULL_AREA}, .function=Display[NTP_TIME]} } }; }; My main.cpp : DisplayTemplate dt; AreaFormat af; dt.displayStyle[BASIC][AREA0].function(af); But compile show error as below : error: must use '.' or '->' to call pointer-to-member function in '((DisplayTemplate*)this)->DisplayTemplate::Display[0] (...)', e.g. '(... ->* ((DisplayTemplate*)this)->DisplayTemplate::Display[0]) (...) In array displayStyle function is equal DisplayTemplate::Display function, but why i can't call function?
Syntax to call a member function when you have a pointer to member function is: (obj.*memberFuncPtr)(args); so you should: DisplayTemplate dt; auto ptr = dt.displayStyle[BASIC][AREA0].function; auto af = dt.displayStyle[BASIC][AREA0].areaParameter; (dt.*ptr)(af); If auto is not clear, you can add alias type for member function pointer using FuncMemPtr = void (DisplayTemplate::*)(AreaFormat); to DisplayTemplate, then: DisplayTemplate::FuncMemPtr ptr = dt.displayStyle[BASIC][AREA1].function;
69,463,774
69,464,031
Adding number to pointer value
I am trying to add a number to a pointer value with the following expression: &AddressHelper::getInstance().GetBaseAddress() + 0x39EA0; The value for the &AddressHelper::getInstance().GetBaseAddress() is always 0x00007ff851cd3c68 {140700810412032} should I not get 0x00007ff851cd3c68 + 0x39EA0 = 7FF81350DB08 as a result? while I am getting: 0x00007ff851ea3168 or sometimes 0x00007ff852933168 or some other numbers. Did I took the pointer value incorrectly?
With pointer arithmetic, type is taken into account, so with: int buffer[42]; char* start_c = reinterpret_cast<char*>(buffer); int *start_i = buffer; we have start_i + 1 == &buffer[1] reinterpret_cast<char*>(start_i + 1) == start_c + sizeof(int). and (when sizeof(int) != 1) reinterpret_cast<char*>(start_i + 1) != start_c + 1 In your case: 0x00007ff851ea3168 - 0x00007ff851cd3c68) / 0x39EA0 = 0x08 and sizeof(DWORD) == 8.
69,464,490
69,464,716
How to make a function that accepts another one with variable arguments
I need a function My_func that works like this auto f = [](string s, double c) { return c; }; assert(My_func(f)(std::make_tuple("Hello", 8.5)) == f("Hello", 8.5')); Now i have template <class T> auto My_func(T&& f) { return [f = std::forward<T>(f)](auto&& value) { }; } What should i add?
I believe you are looking for std::apply #include <cassert> #include <string> #include <tuple> template <class F> constexpr auto My_func(F&& f) { return [f = std::forward<F>(f)](auto&& tuple) mutable { return std::apply(std::forward<decltype(f)>(f), std::forward<decltype(tuple)>(tuple)); }; } int main() { auto f = [](std::string s, double c) { return c; }; assert(My_func(f)(std::make_tuple("Hello", 8.5)) == f("Hello", 8.5)); } This is essentially just a functor wrapper for std::apply, that is still useful because it would not be possible to pass it around due to it being a template.
69,464,493
70,393,053
Capture YUV frames from OpenCV capture device
I need to extract YUV frames directly from a web camera using OpenCV from C++ on the Windows platform. In other words: a setup in OpenCV that makes the capture device's read() method return a YUV Mat. I'm looking for a working example or documentation on how to do this. The specific YUV subformat isn't that important for starters. The camera can produce YUV output. I cannot simply convert a BGR Mat to YUV - I need to capture it from the device without any conversions. So far I've tried and combined connecting using several specific APIs (CV_CAP_DSHOW, CV_CAP_FFMPEG, CV_CAP_GSTREAMER, etc.) changing between different FOURCCs (MJPG, UYVY, etc.) toggling the CAP_PROP_CONVERT_RGB setting to find out what CAP_PROP_MODE might do All to no avail as I'm still just getting output in BGR. So, any hints, links, three-liners? (I'm using OpenCV 4.5.2)
Seems that OpenCV under windows is made with Direct Show which cannot grab YUV variants directly. So the solution is not to use OpenCV but Windows Media Foundation. OpenCV under other OS'es may be able to grab YUV.
69,464,759
69,464,998
Compiler changes the type variable type from uin16_t to int when it's marked as constexpr
I've encountered a weird problem trying to flip all bits of my number. #include <cstdint> constexpr uint16_t DefaultValueForPortStatus { 0xFFFF }; void f(uint16_t x) { } int main() { f(~(DefaultValueForPortStatus)); } When I'm compiling this program (GCC trunk) I'm getting an error: warning: unsigned conversion from 'int' to 'uint16_t' {aka 'short unsigned int'} changes value from '-65536' to '0' [-Woverflow] When I remove constexpr from type specifier, then no warning appears. Why is that? Why does the uint16_t constexpr variable is being changed by the compiler to int, whereas in the case of non-constexpr everything is fine?
This is caused by IMHO a quite unfortunate C++ rule about integer promotion. It basically states that all types smaller than int are always promoted to int if int can represent all values of the original type. Only if not, unsigned int is chosen. std::uint16_t on standard 32/64-bit architectures falls into the first category. int is guaranteed to be at least 16-bit wide, if that would happen to be the case, unsigned int would have been chosen, so the behaviour of the code is implementation-defined. I do not know precisely why the compiler issues the warning only for constexpr values, most likely because it could easily propagate that constant through the ~. In other cases, someone might change DefaultValueForPortStatus to some "safe" value that won't overflow when negated and converted from int back to std::uint16_t. But the issue is there regardless of constness, you can test it with this code: #include <type_traits> #include <cstdint> constexpr uint16_t DefaultValueForPortStatus { 0xFFFF }; int main() { auto x = ~(DefaultValueForPortStatus); static_assert(std::is_same_v<decltype(x), int>); } Relevant Standard sections: expr.conv.prom-7.3.7 - The first few paragraphs. expr.unary.op-7.6.2.2.10 - The last paragraph, states that "Integer promotion" is applied. expr.arith.conv-7.4 - Only applies for binary operators, still contains similar rules.
69,464,843
69,470,253
Is it possible to get mac addresses when scanning networks? ESP32
I need to get the RSSI of the networks and they MAC addresss to a IPS (indoor position system) program. I was able to get ssid, signal strength and security using the sample code, but not mac addresses. I tryed to use this, but itsn't working: void loop() { int n = WiFi.scanNetworks(); if(n == 0){ Serial.println("no networks found"); } else{ for (int i = 0; i < n; ++i) { Serial.print(i + 1); Serial.print(": "); Serial.print(WiFi.SSID(i)); Serial.print(" ("); Serial.print(WiFi.RSSI(i)); Serial.print(")"); Serial.println((WiFi.encryptionType(i) == WIFI_AUTH_OPEN)?" ":"*"); Serial.println(WiFi.macAddress(i)); delay(10); } } delay(10000); }
@Tarmo's answer is correct, but the Arduino core does provide a simpler interface to getting the AP's access point without having to directly call ESP-IDF functions. Use the BSSID method to get the MAC address of the base station's wifi radio. You can call either the BSSID() method to get a pointer to the six byte MAC address or BSSIDstr() to get the MAC address as a string. So for instance: Serial.print(WiFi.BSSIDstr(i)); will print the MAC address as a string. When you're stuck on this kind of things referring to the library's source code can help you find out more than documentation and tutorials may.
69,464,943
69,466,360
How to check a value for null when using boost json ptree
I 'm getting a json response from a server of the following format : {"value": 98.3} However there are cases that the response can be : {"value": null} I have written a C++ program that uses boost json in order to parse this and get the value as float #include <iostream> #include <string> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/foreach.hpp> using namespace std; namespace pt = boost::property_tree; int main(int argc, char **argv) { try { float valuef; pt::ptree root; std::stringstream ss; string result; std::ifstream file("test.json"); if (file) { ss << file.rdbuf(); file.close(); } pt::read_json(ss, root); auto value = root.get<string>("value"); if (value != "null") { valuef = stof(value); } cout <<"float value is" << valuef << endl; } catch (std::exception &e) { string err = e.what(); cout << "error is " << endl << err << endl; } } So I always check if the value is not equal with the literal "null" because according to this Boost Json with null elements outputting nulls is not supported. Since the post is 7 years old I was wondering whether the latest boost libraries support something more generic to check for null values ?
Using the boost/property_tree/json_parser.hpp you can only check the string version like you said: So I always check if the value is not equal with the literal "null" because according to this Boost Json with null elements outputting nulls is not supported. However, since boost version 1.75.0, you can also use boost/json.hpp for working with JSON objects. A parsed JSON object is now of type json::value and the types are specified with json::kind. See boost.org's example. Thus, with the value you would be able to do something like: // jv is a value from a kvp-pair if(jv.is_null()) { // Json value is null } Refer to the boost's example for the implementation specifics.
69,465,479
69,465,612
Unreal Engine 5 crashing after using SetupAttachment function
I've created new poject and added new c++ class, but after using SetupAttachment UE has an error. I've tryed to fix it and found a probem. For now i don't know, in what problem, i actualy know the place. UE5 window after building Code: Header: // Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Pawn.h" #include "TankController.generated.h" class USpringArmComponent; class UCameraComponent; UCLASS() class TANKS_API ATankController : public APawn { GENERATED_BODY() public: // Sets default values for this pawn's properties ATankController(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; //DEFINTE COMPONENTS // // Do a Hull of the Tank UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Components") UStaticMeshComponent* Hull; // Wheels for the Tank UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Components") UStaticMeshComponent* Wheel1; UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Components") UStaticMeshComponent* Wheel2; //Tower of the Tank UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Components") UStaticMeshComponent* Turret; UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Components") UStaticMeshComponent* Barrel; UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Components") UStaticMeshComponent* RecoilSystem; // Camera Components UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Components") USpringArmComponent* SpringArm; UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Components") UCameraComponent* Camera; public: // Called to bind functionality to input virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override; }; And cpp: // Fill out your copyright notice in the Description page of Project Settings. #include "TankController.h" #include "GameFramework/SpringArmComponent.h" // Sets default values ATankController::ATankController() { // Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = false; // Set Root Component to ours Hull RootComponent = Hull; // Attach Wheels to the Hull // Here i have an error SpringArm->SetupAttachment(Hull); } // Called when the game starts or when spawned void ATankController::BeginPlay() { Super::BeginPlay(); } // Called to bind functionality to input void ATankController::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); } How to fix this errror? Is it mine mistake, or UE bug?
It’s your mistake. You’re never initializing SpringArm, and even if it were set in your actor instance (or through a blueprint or subclass), it wouldn’t be available during the constructor (and would still crash when constructing the CDO).
69,465,711
69,465,789
Using a template function as a template param in another function
I was wondering, how I can do the following in C++? template <typename T> T doSomething(T x, T y) { T result = /*do something*/; return result; } template <typename T , typename V> T doMore(**input doSomething as template**, V v){ T result = doSomething<V>(v,0); return result; } I am basically trying to use a template function with its template valuetype in another function as such, is there any way to do that?
You cannot pass (the set of) function template as argument (you can pass specific instantiation though). You might pass functor to solve your issue: template <typename T> T doSomething(T x, T y) { T result = /*do something*/; return result; } template <typename F, typename V> T doMore(F f, V v){ T result = f(v, V{0}); return result; } And then doMore([](auto x, auto y){ return doSomething(x, y); }, 42);
69,466,142
69,467,453
make an array where the number that i insert gets deleted and is replaced by a 0 at end of array using pointers
I'm making it in a 3x4 matrix form Also I'm not sure how to use a pointer since the number that I want to change and replace is an arr[3][4] and not the usual arr[5] using namespace std; #include <iomanip> int main(){ int i; int j; int *change; int number; // not sure how to use the pointer to reference a [3][4] array // int arr[3][4] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; for (int i = 0; i < 3; i++) // not sure if there is a way where i dont have to write every number and just have it go from 1 to 12 // { for (int j = 0; j < 4; j++) { cout << setw(8)<<arr[i][j] << ' '; // to make it look organized and aligned// } cout <<endl; } cout << "number" << ' '; cin >> number; // i woud insert the number here// cout << arr[3][4]; return 0; } and should appear like this (say i chose 6) 1 2 3 4 5 7 8 9 10 11 12 0
The operation that you want to do is natural for single dimensional ranges, and not for multi dimensional ones. There are standard algorithms to achieve your goal with a single dimensional range. With range views, it's fairly simply to get a single dimensional view of the elements: // flat view of the array auto flat_arr = arr | std::ranges::views::join; // move elements to overwrite the removed elements auto remaining = std::ranges::remove(flat_arr, number); // fill the ramaining space with zeroes std::ranges::fill(remaining, 0); Without using ranges, you could achieve the same by defining a custom iterator. Alternatively, you could use a single dimensional array, and transform two dimensional indices with a bit of math. Example: constexpr std::size_t rows = 3, cols = 4; int arr[rows*cols] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; // move elements to overwrite the removed elements auto last_it = std::remove(std::begin(arr), std::end(arr), number); // fill the ramaining space with zeroes std::fill(last_it, std::end(arr), 0); for (std::size_t i = 0; i < rows; i++) { for (std::size_t j = 0; j < cols; j++) { std::cout << std::setw(8) // transform 2D to 1D << arr[i * cols + j] << ' ' ; } std::cout << '\n'; }
69,466,282
69,466,504
Initializing C++ class attribute from another class
Currently, I am trying to implement what I have learned so far: OOP class in C++. Here I have two different classes: VehicleInfo and Vehicle. Here down below is my written code: #include <iostream> #include <string> #include <fstream> #include <math.h> #define M_PI 3.1416 using namespace std; class VehicleInfo{ public: string brand; bool electric; int catalogue_price; float tax_percentage = 0.05; VehicleInfo(string brand, bool electric, int catalogue_price){ VehicleInfo::brand = brand; VehicleInfo::electric = electric; VehicleInfo::catalogue_price = catalogue_price; } float compute_tax(){ if (VehicleInfo::electric == true){ tax_percentage = 0.02; } return VehicleInfo::catalogue_price * tax_percentage; } void print_vehicle_info(){ std::cout << "Brand : " << brand << std::endl; std::cout << "Payable Tax : " << compute_tax() << std::endl; } }; class Vehicle{ public: string id; string license_plate; VehicleInfo vehicle; Vehicle(string id, string license_plate, VehicleInfo vehicle){ Vehicle::id = id; Vehicle::license_plate = license_plate; Vehicle::vehicle = vehicle; } string getName(){ return Vehicle::vehicle.brand; } int getTax(){ return Vehicle::vehicle.compute_tax(); } void print_vehicle(){ std::cout << "ID : " << id << std::endl; std::cout << "License Plate : " << license_plate << std::endl; std::cout << "Brand : " << getName() << std::endl; std::cout << "Tax : " << getTax() << std::endl; } }; int main(int argc, char const *argv[]) { cout << endl; VehicleInfo unit1 = VehicleInfo("Tesla Model 3", true, 60000); unit1.print_vehicle_info(); Vehicle unit2 = Vehicle("YU2314", "KL0932", unit1); unit2.print_vehicle(); std::cin.get(); return 0; } What I expect from the code is that the attribute 'vehicle' in class Vehicle would initialize using attribute and function 'compute_tax()' from class VehicleInfo. Error code I received showed like this: cohesion_coupling.cpp: In constructor 'Vehicle::Vehicle(std::__cxx11::string, std::__cxx11::string, VehicleInfo)': cohesion_coupling.cpp:42:70: error: no matching function for call to 'VehicleInfo::VehicleInfo()' Vehicle(string id, string license_plate, VehicleInfo vehicle){ ^ cohesion_coupling.cpp:17:9: note: candidate: 'VehicleInfo::VehicleInfo(std::__cxx11::string, bool, int)' VehicleInfo(string brand, bool electric, int catalogue_price){ ^~~~~~~~~~~ cohesion_coupling.cpp:17:9: note: candidate expects 3 arguments, 0 provided cohesion_coupling.cpp:10:7: note: candidate: 'VehicleInfo::VehicleInfo(const VehicleInfo&)' class VehicleInfo{ ^~~~~~~~~~~ cohesion_coupling.cpp:10:7: note: candidate expects 1 argument, 0 provided cohesion_coupling.cpp:10:7: note: candidate: 'VehicleInfo::VehicleInfo(VehicleInfo&&)' cohesion_coupling.cpp:10:7: note: candidate expects 1 argument, 0 provided Any suggestion to improve the code (or perhaps some corrections needed on class practices that I have done) ?
In your Vehicle constructor, the compiler first has to default-construct all the member variables. Only after that will the code in the constructor run and Vehicle::vehicle = vehicle; will get called. So your vehicle member variable will first get default-constructed and then assigned a value. But your VehicleInfo does not have a default constructor, which is the error you're getting. To get around this, use member initializers like so: Vehicle(string id, string license_plate, VehicleInfo vehicle) : id(id), license_plate(license_plate), vehicle(vehicle) { }
69,467,219
69,467,562
"The associated constraints are not satisfied" with custom requires clause
In one of my projects, I'm getting the error "the associated constraints are not satisfied" for one of my C++20 concepts. It appears to me that my code is correct, so I must misunderstand something about the language. I have rewritten the code to remove all of the obviously extraneous details. Here are the include statements: #include <array> #include <memory> The constraint I'm defining is on the member function Afunc below: template<typename BLikeType> class A { public: A(std::shared_ptr<C> c_) : c_(std::move(c_)) {} template<typename... Args> requires requires (BLikeType t, Args... args) { {t.Bfunc(c_->Cfunc(args...))}; } std::array<double, sizeof...(Args)> Afunc(Args... args) { return c_->Cfunc(args...); } private: std::shared_ptr<C> c_; }; The classes B and C were written in a way to try to satisfy the constraint above. I use an std::array<double, 2> only so that readers understand that the variadic template in A is necessary. class C { public: C() {} std::array<double, 2> Cfunc(double a, double b) { return { a, b }; } }; I have also written a class B for the template parameter BLikeType in A. It is given below: class B { public: B(){} double Bfunc(std::array<double, 2> my_array) { return my_array[0] + my_array[1]; } }; I then try to test this constraint in my main function: int main() { C c{}; std::shared_ptr<C> c_ptr = std::make_shared<C>(c); A<B> a(c_ptr); std::array<double, 2> answer = a.Afunc<double, double>(.1, .2); // Error: the associated constraints are not satisfied return 0; } Why does this give the error that my constraint is not satisfied?
template<typename... Args> requires requires (BLikeType t, Args... args) { {t.Bfunc(c_->Cfunc(args...))}; } std::array<double, sizeof...(Args)> Afunc(Args... args) { return c_->Cfunc(args...); } The requires-clause is not a complete-class context, so it can't see later-declared class members like c_. You can move the declaration of c_ earlier in the class, but even then it won't see it with any necessary cv-qualification if the function is const (since the function declarator isn't seen at that point). Using a trailing requires-clause can solve that issue. In this case there's no extra cv-qualification to add, though, so it doesn't really matter.
69,467,232
69,606,086
how to get per test coverage for google tests c++ with gcov
I would like to get per test coverage for every test case in my c++ program. What I get is that GoogleTest allows some actions to be performed before and after every test #pragma once #include <gtest/gtest.h> #include <gcov.h> class CodeCoverageListener : public ::testing::TestEventListener { public: virtual void OnTestProgramStart(const ::testing::UnitTest&) {} virtual void OnTestIterationStart(const ::testing::UnitTest&, int) {} virtual void OnEnvironmentsSetUpStart(const ::testing::UnitTest&) {} virtual void OnEnvironmentsSetUpEnd(const ::testing::UnitTest&) {} virtual void OnTestCaseStart(const ::testing::TestCase&) {} virtual void OnTestPartResult(const ::testing::TestPartResult&) {} virtual void OnTestCaseEnd(const ::testing::TestCase&) {} virtual void OnEnvironmentsTearDownStart(const ::testing::UnitTest&) {} virtual void OnEnvironmentsTearDownEnd(const ::testing::UnitTest&) {} virtual void OnTestIterationEnd(const ::testing::UnitTest&, int) {} virtual void OnTestProgramEnd(const ::testing::UnitTest&) {} virtual void OnTestStart(const ::testing::TestInfo& test_info) { __gcov_reset(); } virtual void OnTestEnd(const ::testing::TestInfo& test_info) { __gcov_dump(); } }; And then you tell GoogleTest about this ::testing::UnitTest::GetInstance()->listeners() .Append(new CodeCoverageListener); But during compilation with gcc4.8.5 I get error: fatal error: gcov.h: No such file or directory #include <gcov.h> How to tell gcc where to look for this include? During compilation with gcc8.4.1 I get linker error: g++ -lgcov gcov.cpp /tmp/ccK7o95R.o: In function `main': gcov.cpp:(.text+0x5): undefined reference to `__gcov_reset()' collect2: error: ld returned 1 exit status How to link gcov to c++ program?
The gcov.h header is internal to GCC, so it is not installed in any include path. If you want to call the gcov functions yourself (which I don't recommend), then you would have to declare them yourself. extern void __gcov_reset (void); extern void __gcov_dump (void); Linking with libgcov should work, with the caveat that it is a static library.
69,467,271
69,475,731
CopyFile() function causes exception while debugging but not while running from terminal
I have a Visual Studio 2019 project, containing only one .cpp file, named as copyFile.cpp #undef UNICODE #include <iostream> #include <Windows.h> int main() { std::cout << "Hello World!\n"; DWORD ret = CopyFile("xyz.txt", "xyzCopy.txt", FALSE); printf("\n\t ret: %d, getlasterror(): %d", ret, GetLastError()); return 0; } There is a problem while debugging the code, stepping over this line: DWORD ret = CopyFile("xyz.txt", "xyzCopy.txt", FALSE); causes an exception to be thrown. Exception thrown at 0x76E4B1AF (combase.dll) in copyFile.exe : 0xC0000005: Access violation reading location 0x00000008 then the program breaks. Meanwhile, xyzCopy.txt is being created, with a fresh new modify date but as an empty file, 0 KB. On the other hand, if I run the .exe via terminal by ./copyFile.exe, no exception is being thrown, and code execution continues to the below lines. The file xyzCopy.txt is being created, the content is full (not empty), however, the timestamp of creation is same as the original file. On contrast with the case while debugging. Also, if CopyFile() fails, for example because of not being able to find the source file to be copied, the debugging works fine. So, the problem arises only if CopyFile() succeeds. I have no idea what is the case. Thanks for helping.
I could not find the root cause, however, @SimonMourier posted a link in his comments, which suggest a workaround that works. Additional information: Toggling the debug option "Automatically close the console when debugging stops" on, stops the exception being thrown.
69,467,461
69,468,279
Double template argument for a template function
What would be a valid definition of this function to be called in main as the following? foo<float, double>(sqrtfunction< float>, floatList); I was wondering if it’s done with template classes, but isn't possible to do this without calling it as a member of a class? foo is a function which calls sqrtfunction which applies the sqrtfunction to every element in the "floatList" and returns the list in type of float in this case (type of the sqrtfunction). Whereas the output of foo is saved in a vector instance of type double.
I think user 463035818's answer resolved your problem. But if you want to write a template function, you can write something like this: #include <cmath> #include <iostream> #include <iterator> #include <algorithm> #include <vector> #include <functional> template <typename T> T my_sqrt(T value) { return std::sqrt(value); } template <typename I, typename ElementType> auto sqrt_function(std::function<I(I)> sqrt_func, const std::vector<I>& elements) -> std::vector<ElementType> { std::vector<ElementType> results; std::transform(elements.cbegin(), elements.cend(), std::back_inserter(results), sqrt_func); return results; } int main() { std::vector<double> results = sqrt_function<float, double>(my_sqrt<float>, std::vector<float>(10, 9.f)); std::copy(results.cbegin(), results.cend(), std::ostream_iterator<double>(std::cout, ", ")); } And if you want to use template template parameter you can modify above code like below template <typename I, template<typename> class List, typename ElementType> auto sqrt_function(std::function<I(I)> sqrt_func, const List<I>& elements) -> std::vector<ElementType> { std::vector<ElementType> results; std::transform(elements.cbegin(), elements.cend(), std::back_inserter(results), sqrt_func); return results; } int main() { std::vector<double> results = sqrt_function<float, std::vector, double>(my_sqrt<float>, std::vector<float>(10, 9.f)); std::copy(results.cbegin(), results.cend(), std::ostream_iterator<double>(std::cout, ", ")); }
69,467,769
69,468,161
Compiler version in C++ vs pre-compiled C libraries
I have a code that uses std=c++20. I want to use a C library that was build with old gcc version. Should I recompile the C library using the same compiler ? If no, how could you judge that the 2 ABIs are compatible?
There should be no problem using the library as it is. Don't forget to add extern "C" around the function prototypes. More info: Using C Libraries for C++ Programs
69,467,772
69,468,150
Move (or copy) capture variadic template arguments into lambda
I am attempting to figure out how to move (or just copy if a move is not available) variadic parameters into a lambda within a templated function. I am testing this with a move-only class (see below) because this would be the "worst-case" that needs to work with my template. class MoveOnlyTest { public: MoveOnlyTest(int a, int b = 20, int c = 30) : _a(a), _b(b), _c(c) { std::cout << "MoveOnlyTest: Constructor" << std::endl; } ~MoveOnlyTest() { std::cout << "MoveOnlyTest: Destructor" << std::endl; } MoveOnlyTest(const MoveOnlyTest& other) = delete; MoveOnlyTest(MoveOnlyTest&& other) : _a(std::move(other._a)), _b(std::move(other._b)), _c(std::move(other._c)) { std::cout << "MoveOnlyTest: Move Constructor" << std::endl; other._a = 0; other._b = 0; other._c = 0; } MoveOnlyTest& operator=(const MoveOnlyTest& other) = delete; MoveOnlyTest& operator=(MoveOnlyTest&& other) { if (this != &other) { _a = std::move(other._a); _b = std::move(other._b); _c = std::move(other._c); other._a = 0; other._b = 0; other._c = 0; std::cout << "MoveOnlyTest: Move Assignment Operator" << std::endl; } return *this; } friend std::ostream& operator<<(std::ostream& os, const MoveOnlyTest& v) { os << "{a=" << v._a << "}"; return os; } private: int _a; int _b; int _c; }; And here is the test code I am attempting to get working: void test6() { std::cout << "--------------------" << std::endl; std::cout << " TEST 6 " << std::endl; std::cout << "--------------------" << std::endl; MoveOnlyTest v(1, 2, 3); test6_A(std::move(v)); } void test6_A(MoveOnlyTest v) { std::cout << "test6_A()" << std::endl; test6_B(test6_C, v); } template <typename ... ARGSF, typename ... ARGS> void test6_B(void(*fn)(ARGSF...), ARGS&&... args) { std::cout << "test6_B()" << std::endl; //What do I need to get args to be moved/copied into the lambda auto lambda = [fn, args = ???]() mutable { (*fn)( std::forward<ARGS>(args)... ); }; lambda(); } void test6_C(MoveOnlyTest v) { std::cout << "test6_C()" << std::endl; std::cout << "v = " << v << std::endl; } I am trying to have the exact same behavior as below, only using a generic template so that I can create a lambda which captures and arguments, and calls any function with those arguments. void test5() { std::cout << "--------------------" << std::endl; std::cout << " TEST 5 " << std::endl; std::cout << "--------------------" << std::endl; MoveOnlyTest v(1, 2, 3); test5_A(std::move(v)); } void test5_A(MoveOnlyTest v) { std::cout << "test5_A()" << std::endl; auto lambda = [v = std::move(v)]() mutable { test5_B(std::move(v)); }; lambda(); } void test5_B(MoveOnlyTest v) { std::cout << "test5_B()" << std::endl; std::cout << "v = " << v << std::endl; } To be clear, I don't want to perfectly capture the arguments as in c++ lambdas how to capture variadic parameter pack from the upper scope I want to move them if possible and, if not, copy them (the reason being is that I plan to store this lambda for later execution thus the variables in the stack will no longer be around if they are just captured by reference).
To be clear, I don't want to perfectly capture the arguments as in c++ lambdas how to capture variadic parameter pack from the upper scope I want to move them if possible Just using the same form: auto lambda = [fn, ...args = std::move(args)]() mutable { (*fn)(std::move(args)...); }; In C++17, you could do: auto lambda = [fn, args = std::tuple(std::move(args)...)]() mutable { std::apply([fn](auto&&... args) { (*fn)( std::move(args)...); }, std::move(args)); };
69,468,027
69,468,484
What is the best alternative to C's nested array designators in C++ for initializing a 2D array?
I am currently trying to convert my small regular expression engine from C to C++. To discard syntactically incorrect regexes in a compact way, I use a 2D array to define what kinds of tokens are allowed after one another: #define NUMBER_OF_TOKEN_KINDS 15 typedef enum { Literal, Alternator, ... } TokenKind; bool grammar_allowed[NUMBER_OF_TOKEN_KINDS][NUMBER_OF_TOKEN_KINDS] = { ... [Literal][Alternator] = true, [Alternator][Literal] = true, ... } With this kind of structure you can easily catch a big percentage of syntax errors by checking if grammar_allowed[previous_token][current_token] is set. This way of initializing grammar_allowed doesn't work in C++, because nested array designators are not part of the language. I can think of two working alternatives to the code above, but both have drawbacks: Just don't use designators to initialize entries in the array. This makes it significantly less readable, because I can't see at a glance which entry corresponds to which tokens. It would also be annoying to add/remove tokens or fix a wrong initialization. private: static constexpr bool m_grammar_allowed[NUMBER_OF_TOKEN_KINDS][NUMBER_OF_TOKEN_KINDS] = { {false, true, true, false, false, true, ...}, ... } Initialize the entries line by line in a constructor. This doesn't lose readability but is slower, because the data has to be loaded in at runtime instead of being stored in the executable itself. Lexer() { ... m_grammar_allowed[Literal][Alternator] = true; m_grammar_allowed[Alternator][Literal] = true; ... } Is there any other way to initialize a 2D array like this in C++, but without sacrificing readability or performance? Thank you!
You might create a constexpr function to initialize your std::array (instead of C-array): constexpr std::array<std::array<bool, NUMBER_OF_TOKEN_KINDS>, NUMBER_OF_TOKEN_KINDS> make_grammar_allowed() { std::array<std::array<bool, NUMBER_OF_TOKEN_KINDS>, NUMBER_OF_TOKEN_KINDS> res {}; res[Literal][Alternator] = true; res[Alternator][Literal] = true; // ... return res; } and static constexpr std::array<std::array<bool, NUMBER_OF_TOKEN_KINDS>, NUMBER_OF_TOKEN_KINDS> m_grammar_allowed = make_grammar_allowed();
69,468,326
69,468,374
Reading lines of txt file into array prints only the last element
First of all, I didn't code in C++ for more then 8 years, but there is a hobby project I would like to work on where I ran into this issue. I checked a similar question: Only printing last line of txt file when reading into struct array in C but in my case I don't have a semicolon at the end of the while cycle. Anyway, so I have a nicknames.txt file where I store nicknames, one in each line. Then I want to read these nicknames into an array and select one random element of it. Example nicknames.txt: alpha beta random nickname ... Pirate Scrub Then I read the TXT file: int nicknameCount = 0; char *nicknames[2000]; std::string line; std::ifstream file("nicknames.txt"); FILE *fileID = fopen("asd.txt", "w"); while (std::getline(file, line)) { nicknames[nicknameCount++] = line.data(); // (1) fprintf(fileID, "%i: %s\n", nicknameCount - 1, nicknames[nicknameCount - 1]); } int randomNickIndex = rand() % nicknameCount; // (2) for (int i = 0; i < nicknameCount; i++) fprintf(fileID, "%i: %s\n", i, nicknames[i]); fprintf(fileID, "Result: %s\n", nicknames[randomNickIndex]); fprintf(fileID, "Result: %i\n", randomNickIndex); fclose(fileID); exit(0); What then I see at point (1) is what I expect; the nicknames. Then later at point (2) every single member of the array is "Pirate Scrub", which is the last element of the nicknames.txt. I think it must be something obvious, but I just can't figure it out. Any ideas?
line.data() returns a pointer to the sequence of characters. It is always the same pointer. Every time you read a new line, the contents of line are overwritten. To fix this, you will need to copy the contents of line. Change: char *nicknames[2000]; to char nicknames[2000][256]; and nicknames[nicknameCount++] = line.data(); to strcpy(nicknames[nicknameCount++], line.data()); However, using a vector to store the lines is probably better, since this is C++
69,468,530
69,517,461
why is the overload resolution wrong here?
suppose we have this as our setup: #include <iostream> class Base { private: int a; public: Base(int a) : a(a) { } virtual void print() = 0; }; class Child : public Base { public: using Base::Base; void print() override { //some code } }; class Wrapper { private: void* base_ptr = nullptr; public: Wrapper(void* base_ptr) : base_ptr(base_ptr) { std::cout << "void* version called\n"; } Wrapper(Base* const& base_ptr) : base_ptr(base_ptr) { std::cout << "Base*const& version called\n"; } }; if we do the following: Child* child_ptr = new Child(1); Wrapper w(child_ptr); output is: Base*const& version called which is expected and completely normal. but if we change Wrapper(Base *const&) to Wrapper(Base*&) we call the void* version: class Wrapper { private: void* base_ptr = nullptr; public: Wrapper(void* base_ptr) : base_ptr(base_ptr) { std::cout << "void* version called\n"; } Wrapper(Base*& base_ptr) : base_ptr(base_ptr) { std::cout << "Base*const& version called\n"; } }; int main() { Child* child_ptr = new Child(1); Wrapper w(child_ptr); return 0; } for this version we get this output: void* version called but why is that? shouldn't Base*const& just make it also compatible with temporary objects?
Ok. after sometime thinking about it, I figured it out. It's simply because there is an implicit cast happening where we try to call the constructor of second version, we change the type of Child* to Base* and because of that it's not anymore an LValue and becomes an RValue, therefore it can't bind to Base*& and if we were about to change its signature to Base*&&, it would choose this overload(which is expected because of the implicit cast happening there and making it an RValue).
69,468,579
69,470,901
Save data from `recvfrom()` to a structure to avoid extra bytes?
I get the packages by upd and create the structure PSG. Then I save it to a vector and sort.At the end, I write all the byte data to a file. The problem is that the last packet is less than 1424 bytes. and because of this, extra bytes are written to the end of the file. How could I correctly save data from recvfrom() to a structure to avoid extra bytes? #pragma pack(push, 1) struct PSG { uint64_t id; uint64_t size; uint32_t type; uint32_t count; uint8_t data[1400]; }; #pragma pack(pop) PSG psg; std::vector<PSG> psg_vector; while(1) { if ((bytesrecv = recvfrom(m_sock, &psg, 1424, 0, (sockaddr *) NULL, NULL)) < 0) { perror("recvfrom"); close(m_sock); return -1; } psg_vector.push_back(psg); sort(psg_vector.begin(), psg_vector.end(), [](const auto &lhs, const auto &rhs) { return lhs.count < rhs.count; }); for (auto &a: psg_vector) { file.write(reinterpret_cast<const char *>(&a.data), sizeof(a.data)); } }
You're getting the size of the packet read in bytesrecv, but then you're ignoring it and not using it. Store it somewher and use it. You could add it to your PSG object: #pragma pack(push, 1) struct PSG { uint64_t id; uint64_t size; uint32_t type; uint32_t count; uint8_t data[1400]; ssize_t size; }; #pragma pack(pop) PSG psg; std::vector<PSG> psg_vector; while(1) { if ((psg.size = recvfrom(m_sock, &psg, 1424, 0, (sockaddr *) NULL, NULL)) < 0) { perror("recvfrom"); close(m_sock); return -1; } psg_vector.push_back(psg);
69,468,615
69,469,271
I am getting an error of redefinition while using extern header file
I am getting an error of redefinition while using extern, but I was also told, that extern variable should be used like this, why I am getting this error and how should I use extern in this case so it will work? (I can use this variable even if I don't specify it in Tab.cpp, but I am getting error of finding one or more symbols, which was defined 2 times.) Files: Tab.h: #pragma once #include "wx/wx.h" class Tab : public wxFrame { wxDECLARE_EVENT_TABLE(); void close(wxCommandEvent& evt); void init(); public: Tab(); }; Tab.cpp: #include "Tab.h" #include "ids.h" #include "wx/wx.h" int maxid; wxBEGIN_EVENT_TABLE(Tab, wxFrame) EVT_BUTTON(2, Tab::close) wxEND_EVENT_TABLE() Tab::Tab() : wxFrame(nullptr, maxid++, "ERIS 2") { init(); } void Tab::close(wxCommandEvent &evt) { this->Close(); evt.Skip(); } void Tab::init() { wxGridSizer* sizer = new wxGridSizer(10, 10, 0, 0); for(int x = 0; x < 10; ++x) for(int y = 0; y < 10; ++y) { sizer->Add(new wxButton(this, maxid, _(std::to_string(maxid))), wxEXPAND | wxALL); ++maxid; } this->SetSizer(sizer); sizer->Layout(); } ids.cpp: #include "ids.h" std::vector<Object> ids; Object& search(const char* name) { for(std::vector<Object>::iterator it = ids.begin(); it != ids.end(); *++it) if((*it).name == name) return *it; } Object& search(int id) { for(std::vector<Object>::iterator it = ids.begin(); it != ids.end(); *++it) if((*it).id == id) return *it; } void add(Object& obj) { ids.emplace_back(obj); } ids.h: #pragma once #include <vector> #include "wx/wx.h" struct Object { wxObject* obj; const char* name; int id; }; Object& search(const char*); Object& search(int); void add(Object&); extern std::vector<Object> ids; extern int maxid = 0;
There are definitions and declarations. A declaration tells the compiler that something exists. A definition is a declaration that has all the information needed to describe that thing. For global variables like maxid, The extern says that it will have external linkage; that is, be known to the linker and be seen between different source files (translation units). Many different translation units can say extern int maxid; and they all just say "OK, I know about this symbol, I'll find it somewhere eventually.". So, that's fine to put in a header which becomes part of more than one translation unit. However, when you give it an initializer, in this case the =0 (one of several possible ways describe initialization), then it becomes a definition. It causes storage to be allocated and a definite location set up for that variable. You should not do that in a header, because each file that includes it will define the same variable. Thus, at link time you get more than one, which is an error. The legacy way of doing this is to put extern int x; in the header so that everyone knows x exists, and then put int x = 0; in one CPP file so that this variable lives somewhere. Writing extern int x = 0; would mean the same thing but is un-idiomatic. The modern way to handle this is to use a feature created for this express purpose. Put inline int x = 0; in the header file. This will define it in every translation unit that includes it, but they will be marked such that the linker understands that they are all the same and it should just pick one and ignore the others.
69,468,783
69,468,831
Adding derived class object to vector<unique_ptr> of base class
So in my code I'm trying to add unique_ptr to objects from derived class to vector of base class. I get this error: E0304 no instance of overloaded function "std::vector<_Ty, _Alloc>::push_back [with _Ty=std::unique_ptr<Organism, std::default_delete<Organism>>, _Alloc=std::allocator<std::unique_ptr<Organism, std::default_delete<Organism>>>]" matches the argument list The code of base class (if you need more let me know, trying to put as little code as possible): vector<unique_ptr<Organism>> World::generate_organisms(int act_level) { vector<unique_ptr<Organism>> organism_list = get_vector(); coordinates sheep_pos(10, 2); //getting error in next line organism_list.push_back(make_unique<Sheep>(sheep_pos, *this)); return organism_list; } Code of the derived class: .h file class Sheep : Organism { Sheep( coordinates organism_pos, World* world); }; .cpp file Sheep::Sheep( coordinates organism_pos, World* act_world) : Organism(organism_pos, act_world) { this->armor = 0; this->damage = 2; this->health = 10; this->vigor = 10; }
Similar to how the default member visibility of class is private, inheritance is also private unless otherwise specified. You need to inherit from Organism publicly so that std::unique_ptr is able to see and perform the conversions you expect. class Sheep : public Organism { public: Sheep( coordinates organism_pos, World* world); } Your constructor also needs to be public so that std::make_unique can see and use it.
69,468,895
69,469,410
Reverse order of varidic template arguments while constructing a map key
I am using a variadic template to construct a key for a map, calculating a number to a base: template<typename T> uint64_t key(int base, T n) { return uint64_t(n) % base; } template<typename T, typename... Args> uint64_t key(int base, T n, Args... rest) { return key(base, rest...) * base + (uint64_t(n) % base); } Calling it with key(10, 1, 2, 3) gives me a key with decimal value 321. I would prefer to get 123 for the key, and I have found a solution that works: template<typename T> uint64_t keyHelper(int& mul, int base, T n) { mul = base; return uint64_t(n) % base; } template<typename T, typename... Args> uint64_t keyHelper(int& mul, int base, T n, Args... rest) { int mul_tmp; uint64_t result = keyHelper(mul_tmp, base, rest...) + (uint64_t(n) % base) * mul_tmp; mul = mul_tmp * base; return result; } template<typename... Args> uint64_t key(int base, Args... args) { int mul; return keyHelper(mul, base, args...); } This solution feels like a hack, tho, since it passes around a reference to fix the exponent of multiplications. Is there a simple varidic way where the template calculates the number in the required order, i.e. 123? I have seen solutions for reversing variadic arguments, and they seem overly complicated.
Since C++17 I would use fold expression (op,...) to do that: template<class B, class ... Args> auto key(B base, Args ... args) { std::common_type_t<Args...> res{}; ( (res *= base, res += args % base), ... ); return res; } Demo
69,469,112
69,469,226
Template struct in C++ with different data members
Is there a way to change what data members are contained in a templated struct based on the parameters? For instance: template<int Asize> struct intxA { #if (Asize <= 8) int8 num = 0; #elif (Asize <= 16) int16 x = 1; #endif }; In implementation: intxA<3> struct8; intxA<11> struct16; I have tried the code above, however, the data member "num" is always present, no matter the value of Asize. Is there a way to do this in C++ without doing it manually?
Yes, you can do it with partial specialization. template<int Asize, typename = void> struct intxA { }; template <int Asize> struct intxA<Asize, std::enable_if_t<Asize <= 8>> { int8 num = 0; }; template <int Asize> struct intxA<Asize, std::enable_if_t<(Asize > 8 && Asize <= 16)>> { int16 x = 1; };
69,469,207
69,469,611
Access Violation with uninitialized variable being passed to method call that initializes it
I need some theoretical explanation of the following memory access violation BEFORE even entering the method: String testMethod (AnsiString param1); AnsiString A1 = testMethod(A1); I am trying to understand the theory behind the problem. A1 is getting initialized by the return value of testMethod() while at the same time it is passed to testMethod(). What happens before the method is actually entered? When passed to testMethod() it has no actual value/a random value, has it? A local copy of A1 is created, does the exception occur during that process, actually? Trying to debug, a lot of AnsiString, UnicodeString, and AnsiStringBase methods are entered. Why does it work, when I change the method signature this way: AnsiString testMethod (AnsiString param1);
AnsiString A1 = testMethod(A1); When you reach this point: AnsiString A1 the name A1 exists and is known to the compiler. Thus, you can use it farther to the right. However, you are calling testMethod with a raw memory block that has not been constructed yet. That's going to blow up when it hits the copy constructor which tries to read the members inside A1. Here is an elaboration: Although it's all written on one line, you have several steps going on and things handled at different times. At compilation time, a group of bytes are set aside and the label A1 used to refer to them. At run time, a statement is executed to initialize A1. This works by calling a constructor which is designed to expect raw memory and is responsible for making that memory into a legal instance of that type. However, in this case, obtaining the value to use to initialize this variable it uses the function call which passes A1 as a parameter. But A1 has not been initialized yet. At another level of detail, the code is realized the following way: A function returning a class type is implemented by passing the address of the result area as another argument. The definition of A1 caused the compiler to set aside memory for that, but nothing has been done with it yet. At this point in the execution, it calls a function __impl_testMethod(&A1, copy_of(A1));. Trying to debug, a lot of AnsiString, UnicodeString, and AnsiStringBase methods are entered. You are seeing the copy constructor in action. You probably really wanted to define it as: String testFunction (const AnsiString& param1); because there is no reason to duplicate the object into param1 if that function will be looking at it but not modifying its own private copy. And, C++ does not have "methods" but rather member functions, and this isn't even a member function anyway (as far as I can see in your OP). It is properly described as a "free function".
69,469,311
69,469,932
C++ Managing pointers to functions inside another class
I'm trying to write a program that calls for a function stored inside a class whose implementation is defined by another object instance. Let me clarify this better: I would like to create an object A and call for its functions (like an abstract object), but the body of this functions should be defined by either an instance of class B or class C. I know abstract classes exist in C++ and that i could just call the derived objects, but my goal is to call for object A methods without caring (or knowing in advance) whether an instance of object B or C was previously created. I tried to use pointers to functions, unfortunately with no results. My code was something like this Class A: class A { public: static void (*someFunction)(); }; Class B: class B { public: B(){ A::someFunction = someFunction; } private: void someFunction(){ std::cout << "some function" << std::endl; } }; Main code: B b; A::someFunction(); What am I doing wrong or could be done in a more simple and elegant way? Sorry for the poor explaination and thank you in advance for your help.
Polymorphism exists for just this type of situation, eg: class A { public: virtual ~A() = default; virtual void someFunction() = 0; }; class B : public A { public: void someFunction() override { std::cout << "some function" << std::endl; } }; class C : public A /* or B*/ { public: void someFunction() override { std::cout << "some other function" << std::endl; } }; void doIt(A &a) { a.someFunction(); } B b; doIt(b); C c; doIt(c); Online Demo But, if that is not what you want, then consider having A use std::function instead of a raw function pointer. Then B and C can assign whatever they want to A::someFunction using lambdas or std::bind(), eg: A.h: #include <functional> class A { public: static std::function<void()> someFunction; }; A.cpp: #include "A.h" std::function<void()> A::someFunction; B.h: #include "A.h" class B { public: B(){ A::someFunction = [this](){ someFunction(); }; or: A::someFunction = std::bind(&B::someFunction, this); } private: void someFunction(){ std::cout << "some function" << std::endl; } }; C.h: #include "A.h" class C { public: C(){ A::someFunction = [this](){ someFunction(); }; or: A::someFunction = std::bind(&C::someFunction, this); } private: void someFunction(){ std::cout << "some other function" << std::endl; } }; #include "A.h" #include "B.h" #include "C.h" B b; A::someFunction(); C c; A::someFunction(); Online Demo
69,469,481
69,476,872
how to translate key shortcut
I cannot force QKeySequence::toString() to return translated shortcut representation despite the fact that it documentation suggests it should work. The docs say: "The strings, "Ctrl", "Shift", etc. are translated using QObject::tr() in the "QShortcut" context." but I am not completely sure what it means by shortcut context. I am probably doing something wrong... Here is my example. To make it work, I need to copy qtbase_es.qm from Qt installation directory to my project build directory. When the translation is correctly loaded, the action in the menu correctly shows "Action Control+Intro" which is Spanish translation of the shortcut for "Action Ctrl+Enter". But the tooltip on the main window is still "Action (Ctrl+Enter)". I would expect it to be "Action (Control+Intro)", like in the menu. What am I doing wrong? #include <QAction> #include <QApplication> #include <QDebug> #include <QMainWindow> #include <QMenuBar> #include <QTranslator> int main(int argc, char *argv[]) { QTranslator spanish; qDebug() << spanish.load("qtbase_es.qm"); // should return true if correctly loaded QApplication a(argc, argv); QApplication::installTranslator(&spanish); QMainWindow w; auto menu = new QMenu("Menu"); auto action = menu->addAction("Action"); action->setShortcutContext(Qt::ApplicationShortcut); action->setShortcut(Qt::CTRL | Qt::Key_Enter); w.menuBar()->addMenu(menu); w.show(); QApplication::processEvents(); // I also tried this line but it is useless... w.setToolTip(QString("%1 (%2)").arg(action->text(), action->shortcut().toString())); qDebug() << action->shortcut().toString(); // WRONG: returns Ctrl+Enter but I expect Control+Intro return a.exec(); }
The QShortcut::toString has a SequenceFormat parameter, defaulted to ProtableText. The documentation of the format states, that portable format is intended for e.g. writing to a file. The native format is intended for displaying to the user, and only this format performs translations. Try: qDebug() << action->shortcut().toString(QKeySequence::NativeText);
69,470,058
69,470,331
How to read QWORD (64-bit) from the registry in C++?
How do I read a REG_QWORD from the registry? Most specifically the HardwareInformation.qwMemorySize . I found that with it divided by 1024 then once again divided by 1024 you can get the Video memory in megabytes. How can I read the QWORD first? I can only find how to read DWORDs.
You read a QWORD the exact same way you read a DWORD, using RegQueryValueEx(), just with a 64-bit integer variable instead of a 32-bit integer variable, eg: HKEY hKey; if (RegOpenKeyEx(..., KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS) { QWORD value = 0; // or UINT64, ULONGLONG, ULONG64, ULARGE_INTEGER, etc... DWORD dwType, dwSize = sizeof(value); if (RegQueryValueEx(hKey, _T("HardwareInformation.qwMemorySize"), NULL, &dwType, reinterpret_cast<LPBYTE>(&value), &dwSize) == ERROR_SUCCESS) { if (dwType == REG_QWORD || dwType == REG_BINARY) { // use value as needed... } } RegCloseKey(hKey); } Or, using RegGetValue() instead: QWORD value = 0; // see above... DWORD dwSize = sizeof(value); if (RegGetValue(hkey, NULL, _T("HardwareInformation.qwMemorySize"), RRF_RT_QWORD, NULL, &value, &dwSize) == ERROR_SUCCESS) { // use value as needed... }
69,470,252
69,474,948
Examine how the variables are allocated in the heap memory (for debugging runtime errors)
For example, the following code causes munmap_chunk(): invalid pointer #include <vector> int main(int argc, char* argv[]) { std::vector<int> foo(10, 0); std::vector<int> bar(10, 1); for(int i = 0; i < 20; i++) { foo[i] = 42; } bar.clear(); // causes munmap_chunk(): invalid pointer } In this simple example, I can easily guess that bar is allocated after foo in the heap memory, so can guess some operation on foo "break" the memory of bar. so fixing the bug is fairly easy. However in a real application, the situation could be much more complex and we can't easily guess the heap memory allocation. So my question is: Is there way to show how variables are allocated in the heap? Is it possible to monitor which function break certain memory accidentally?
Is there way to show how variables are allocated in the heap? Yes: you can examine locations that vector will use in a debugger. For example (using your program) and GDB: (gdb) start Temporary breakpoint 1 at 0x1185: file t.cc, line 3. Starting program: /tmp/a.out Temporary breakpoint 1, main (argc=1, argv=0x7fffffffdbb8) at t.cc:3 3 std::vector<int> foo(10, 0); (gdb) n 4 std::vector<int> bar(10, 1); (gdb) p/r foo $1 = {<std::_Vector_base<int, std::allocator<int> >> = {_M_impl = {<std::allocator<int>> = {<__gnu_cxx::new_allocator<int>> = {<No data fields>}, <No data fields>}, <std::_Vector_base<int, std::allocator<int> >::_Vector_impl_data> = {_M_start = 0x55555556aeb0, _M_finish = 0x55555556aed8, _M_end_of_storage = 0x55555556aed8}, <No data fields>}}, <No data fields>} (gdb) n 5 for(int i = 0; i < 20; i++) { (gdb) p/r bar $2 = {<std::_Vector_base<int, std::allocator<int> >> = {_M_impl = {<std::allocator<int>> = {<__gnu_cxx::new_allocator<int>> = {<No data fields>}, <No data fields>}, <std::_Vector_base<int, std::allocator<int> >::_Vector_impl_data> = {_M_start = 0x55555556aee0, _M_finish = 0x55555556af08, _M_end_of_storage = 0x55555556af08}, <No data fields>}}, <No data fields>} Here you can see that foo will use locations 0x55555556aeb0 through 0x55555556aed8, and bar will use 0x55555556aee0 through 0x55555556af08. Note however that these locations may change from run to run, especially in multi-threaded programs, making this technique very difficult to use. If your problem can be found by the Address Sanitizer, that would be significantly faster and more reliable approach. Is it possible to monitor which function break certain memory accidentally? Yes: that's what watchpoints are for. For example, we don't expect the location pointed to by foo._M_impl._M_end_of_storage to be changed, so we can set a watchpoint on it: (gdb) start Temporary breakpoint 1 at 0x1185: file t.cc, line 3. Starting program: /tmp/a.out Temporary breakpoint 1, main (argc=1, argv=0x7fffffffdbb8) at t.cc:3 3 std::vector<int> foo(10, 0); (gdb) n 4 std::vector<int> bar(10, 1); (gdb) n 5 for(int i = 0; i < 20; i++) { (gdb) watch *(int*)0x55555556aed8 Hardware watchpoint 2: *(int*)0x55555556aed8 (gdb) c Continuing. Hardware watchpoint 2: *(int*)0x55555556aed8 Old value = 49 New value = 42 main (argc=1, argv=0x7fffffffdbb8) at t.cc:5 5 for(int i = 0; i < 20; i++) { (gdb) p i $1 = 10 <-- voila, found the place where overflow happened.
69,471,180
69,471,591
cpp common method to create QObject::connection
i want to write ConnectMathod(...) in such way that it accept QObject* and receiver slot. and establish connection class A : public QObject { public : A(); ~A(); signals : void sigA(int); slots : void slotA(bool); } class B : public QObject { public : B(); ~B(); signals : void sigB(bool); slots : void slotB(int); } // class C : i want to write common mathod which expect receiver (QObject*) and slot class C : public QObject { public : C(); ~C(); signals : void signalC(bool); // i want help to write ConnectMathod QMetaObject::Connection ConnectMathod(QObject* receiverObject, functionPointer) { QMetaObject::Connection = QObject::connect(this, &C::signalC, receiverObject, functionPointer); return connection; } } /////// main.cpp /////// main() { A objA = new A(); B objB = new B(); C objC = new C(); QMetaObject::Connection connection = objC->ConnectMathod(objA, objA->slotA); connection = objC->ConnectMathod(objB, objB->slotB); }
Make ConnectMethod as a function template which takes as second argument template parameter which will be any callable object, for example a closure generated from lambda expression: class C : public QObject { Q_OBJECT public: C() {} ~C() {} signals: void signalC(bool); public: template<class Callable> QMetaObject::Connection ConnectMathod(QObject* contextObj, Callable cb) { return connect(this, &C::signalC, contextObj, cb); } }; A* a = new A(); B* b = new B(); C* c = new C(); c->ConnectMathod(a, [a](bool){ a->slotA(true); }); c->ConnectMathod(b, [b](bool){ b->slotB(10);}); c->signalC(true);
69,471,424
69,471,541
How C++ alias works?
How does alias internally work in C++? Does it allocate its own memory like pointers? Otherwise how does the compiler treat it? Is it like C++ Macro preprocessor computing? int x=5; int &y=x; //Assembly of this???
Those are called references. The standard doesn't describe how they (or anything else) work on the assembly level. In practice, they are implemented as pointers, unless the compiler optimizes them away (which is easier for references compared to pointers, because they can't be reassigned). They are unrelated to macros, the preprocessor doesn't know about references. The standard contains some interesting wording for references: they "are not objects", the consequence being that you can't legally meaningfully examine their memory layout and modify it. But this is mostly a peculiarity of the wording; for most purposes they work like immutable pointers.
69,471,669
69,471,832
How to get the weekday number from std::chrono::year_month_day in C++
In C++ 20, the following code will output the number (0-6) for the weekday of the input date: #include <chrono> #include <iostream> int main() { using namespace std; using namespace std::chrono; year_month_day dmy; cin >> parse("%d %m %Y", dmy); cout << format("%w", weekday{dmy}) << '\n'; } How can I get that number to use in code as a numeric value so I could use it in a calculation? This has to be simple but I can't figure it out. int total_score = weekday{dmy} * 10; As a side note, I am really using the date (http://howardhinnant.github.io/date/date.html) library created by Howard Hinnant in C++ 17 but I believe the same question applies to both.
You can use std::chrono::weekday::c_encoding to retrieve the stored value.
69,471,738
69,473,051
Reference counting - internal references problem
I have implemented my own smart pointers, and everything worked fine, untill I realized a fatal flaw with my implementation. The problem was the fact that an object can have a smart pointer that potentially holds a reference to itself. the problem would be easy to avoid if this was a one layer problem - what could easly happen is a ref counted class would indirectly (through one of its members) holds a referenece to itself. this would mean that a object would never be removed deleted. Is there any way/method I could solve this? simplest example: class Derived : public Object { public: static ref<Object> Create() { return ref<Object>(new Derived()); } private: Derived() : m_ref(this) // m_ref now holds a reference to Derived instance { // SOME CODE HERE } ref<Object> m_ref; }; Object is base class contains reference counter, ref is smart pointer that holds a reference to its assigned object
There is no easy way to handle this issue. It is a fundamental problem with reference counting. To build intuition as to why this is the case, note that the difficulty of detecting cycles of smart pointers is similar to the difficulty of dealing with the cycles. To detect cycles you need to be able to traverse the pointers from "root pointers". If you could do that, you could mark the ones you see during traversal. If you could mark them you could implement mark-and-sweep, which is garbage collection.
69,471,899
69,477,033
CGAL::Polyhedron_3 makes unwanted duplicated vertices using make_tetrahedron(), how to solve it?
I was trying to create a volume mesh using the CGAL::Polyhedron_3 data structure when, doing some tests, I noticed that the make_tetrahedron function duplicates the vertices already present in the polyhedron. Example: Two tetrahedra that share a common face this is the code I tried: #include <CGAL/Simple_cartesian.h> #include <CGAL/Polyhedron_3.h> #include <iostream> typedef CGAL::Simple_cartesian<double> Kernel; typedef Kernel::Point_3 Point_3; typedef CGAL::Polyhedron_3<Kernel> Polyhedron; typedef Polyhedron::Vertex_iterator Vertex_iterator; int main(void) { // common points Point_3 p( 1.0, 0.0, 0.0 ); Point_3 q( 0.0, 1.0, 0.0 ); Point_3 s( 0.0, 0.0, 0.0 ); // the other two Point_3 r( 0.0, 0.0, 1.0 ); Point_3 d( 0.0, 0.0,-1.0 ); Polyhedron P; P.make_tetrahedron( p, q, r, s ); P.make_tetrahedron( p, q, s, d ); CGAL::IO::set_ascii_mode( std::cout ); // printing out the vertices for ( Vertex_iterator v = P.vertices_begin(); v != P.vertices_end(); ++v ) std::cout << v->point() << std::endl; return 0; } and this is the output I expected to see: 1 0 0 0 1 0 0 0 1 0 0 0 0 0 -1 but that's what I got: 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 0 0 0 -1 Now, the question is: Is it possible to store a point as a vertex only once in CGAL::Polyhedron_3 using the make_tetrahedron function?
You cannot store non-manifold features in a polyhedron, you need something like a linear cell complex. See here
69,471,964
69,472,193
Trouble establishing pipe communication between python and cpp
The first attached piece of code is the python code I was using (in "test.py"). The second one is the c++ code (in "test.cpp" which I compiled to "test.out"). I am using ubuntu (18.04) wsl to run these programs. I firstly established the pipes that will allow intercommunication between the two processes. Using fork I created a child process to call "test.out", which is the executable of the c++ code. I pass the file descriptors as arguments to the called program. #Python import os import subprocess import time #establishing communication pipes r_sub, w_py = os.pipe() r_py, w_sub = os.pipe() #creating a subprocess to run c++ code pid = os.fork() if pid > 0: #Parent os.close(r_sub) os.close(w_sub) print("[Py]Parent process is writing : r_py" + str(r_py) + " w_py" + str(w_py) + "r_sub" + str(r_sub) + " w_sub" + str(w_sub)) text = b"message" #Writing message to c++ .exe os.write(w_py,text) print("[Py]Written text:", text.decode()) os.close(w_py) #Reading c++ message rec = os.fdopen(r_py) print("[Py]Received Message " + rec.read()) else: #Child print("[SubP]Calling c++ .exe : r_sub" + str(r_sub) + " w_sub" + str(w_sub) + " r_py" + str(r_py) + " w_py" + str(w_py)) #Calling .exe of c++ code subprocess.call(["./test.out",str(r_sub),str(w_sub),str(r_py),str(w_py)]) //c++ #include <iostream> #include <stdio.h> #include <unistd.h> #include <string> #define MSGSIZE 16 int main(int argc, char *argv[]) { if(argc < 5){ printf("[c++]File descriptors are not present"); return -1; } printf("[c++]I received file descriptors: r_sub%s w_sub%s r_py%s w_py%s\n",argv[1],argv[2],argv[3],argv[4]); //Arguments are received as character arrays -> turning them to integers to use them as file descriptors int r_sub = std::stoi(argv[1]), w_sub = std::stoi(argv[2]), r_py = std::stoi(argv[3]), w_py = std::stoi(argv[4]); char buffer[MSGSIZE] = ""; close(r_py); close(w_py); //Here I find out that read fails if(read(r_sub,buffer,MSGSIZE) == -1) printf("\n:(\n"); printf("[c++]Received message: %s\n",buffer); //Attempting to send message back to python close(r_sub); write(w_sub,"message back",MSGSIZE); std::cout << "[c++]Finish\n\n"; return 0; } There are neither compilation errors nor "bad file descriptor" errors, but the communication does not work. Actually no information is received in either end. The Results: python3 test.py [Py]Parent process is writing : r_py5 w_py4r_sub3 w_sub6 [Py]Written text: message [SubP]Calling c++ .exe : r_sub3 w_sub6 r_py5 w_py4 [c++]I received file descriptors: r_sub3 w_sub6 r_py5 w_py4 :( [c++]Received message: [c++]Finish [Py]Received Message:
You have some problems in your C++ program (like undefined behavior because you read your string literal out of bounds in write(w_sub, "message back", MSGSIZE);) but the first problem is that your file descriptors aren't inherited by the started program - so they are all bad file descriptors in the C++ program. Always check - don't take anything for granted. You can set the inheritance mode explicitly in python: os.set_inheritable(r_sub, True) # do this for all fds that should be inherited ... or open the pipes with os.pipe2(0) which makes them inheritable by default. And make sure they aren't all closed when you start the sub-process: subprocess.call(["./test.out",str(r_sub),str(w_sub),str(r_py),str(w_py)], close_fds=False) # ^^^^^^^^^^^^^^^
69,472,895
69,473,227
Double becomes pointer when returned?
I'm new to Cpp and I'm just trying to construct a very basic 'Circle' class. Below is my code #include <iostream> #include <cmath> #include <typeinfo> class Circle { private: const double pi = 3.14159265358979323846; double radius; double area; double perimeter; public: void set_rad(double rad){ radius = rad; area = pi*pow(rad,2); perimeter = 2*pi*rad; } double get_attr() { double circle_attr[3] = {radius, area, perimeter}; std::cout << typeid(circle_attr).name() << std::endl; return *circle_attr; } }; int main(){ Circle aCircle; aCircle.set_rad(5); aCircle.get_attr(); return 0; } The code runs and behaves as expected. However, if, in the return line to the method get_attr, I replace *circle_attr with circle_attr , then I get the error cannot convert 'double*' to 'double' in return. However, circle_attr is already an array of doubles. That's what I intialised it as and it's what Cpp is telling me, since when I call typeid(circle_attr).name() I get back A3_d, which I assume is short for Array3_double. So what is going on here?
The actual issue you're having is the attempt to return a C-array from a function. That's not a thing that can be done. If you want, the smallest possible change would be to change your function to look like this: #include <array> // [...] std::array<double, 3> get_attr() { std::array<double, 3> circle_attr{radius, area, perimeter}; std::cout << typeid(circle_attr).name() << std::endl; return circle_attr; } You stated that your function was supposed to return A double, and then you tried returning an array of doubles, or really just the radius in your case. std::array is a bit of a mess, though, since the size is part of the type information. Here's your code, with some tweaks to get it more in line with C++ and also completely rewriting your get_attr() function. #include <cmath> #include <iostream> #include <tuple> // CHANGED: Needed for structured binding usage in get_attr() class Circle { private: const double pi = 3.14159265358979323846; double radius = 0.0; // CHANGED: Kept the default member initialization going double area = 0.0; double perimeter = 0.0; public: Circle() = default; // CHANGED: Added constructors Circle(double r) : radius(r), area(pi * std::pow(radius, 2)), perimeter(2 * pi * radius) {} void set_rad(double rad) { radius = rad; area = pi * pow(rad, 2); perimeter = 2 * pi * rad; } // CHANGED: Using C++17 feature called structured bindings; also made function // const, since it shouldn't alter the data auto get_attr() const { return std::make_tuple(radius, area, perimeter); } }; int main() { Circle aCircle(5.0); // CHANGED: Now we can use constructors // aCircle.get_attr(); // NOTE: Didn't even try to save info anywhere auto [radius, area, perimeter] = aCircle.get_attr(); std::cout << "Radius: " << radius << "\nArea: " << area << "\nPerimieter: " << perimeter << '\n'; return 0; } Output: Radius: 5 Area: 78.5398 Perimieter: 31.4159 We added constructors, which are a fundamental part of C++ OOP. You can see in main() how constructors allow us to initialize at the declaration site. I also left one your original lines in main() to note that even if get_attr() worked, you didn't save the info at all. So you wouldn't have had it anyway. Your get_attr() function has been written to take advantage of a C++17 feature called structured bindings. It also takes advantage of another feature called CTAD, just to keep the one line in get_attr() succinct. In order for you to test this, you'll need to add the -std=c++17 flag to the compile command you're using. It's good practice to always specify the standard version you're using.
69,473,641
69,474,175
Multithreading is slowing down OpenGl loop
I'm currently programing a minecraft like map generator using OpenGL in C++. I have a AMD Rayzen 5 3600 6-Core. So, when I tried to add multithreading in my main loop to call my chunks generation, it was slowing down the rendering. I'm not using multithreading for rendering. I'm on Windows using MinGw to compile code and multithreading works on posix. The problem is I can't figure why it makes my rendering slow. Even if I try to create ONLY ONE thread I loose FPS. And even if I create a thread to do simple task like : std::cout << "Thread #" << i << "\n"; It will slow down the rendering. My compile flags are -pthread -lopengl32 -lglu32 -lgdi32 -luser32 -lkernel32 -lglfw3dll -O3 I'm adding the fact that at school I'm working on MacOS and the multithreading is not slowing down the rendering. I'm assuming a MinGW problem. If you have any kind of idea to help me I will take it. Thank you for your forthcoming responses ! There is my loop : while (!glfwWindowShouldClose(window)) { Frustum frustum; //fps(window); float currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; processInput(window); glClearColor(0.69f, 0.94f, 0.95f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); shader.use(); glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 1000.0f); shader.setMat4("projection", projection); glm::mat4 view = camera.GetViewMatrix(); shader.setMat4("view", view); frustum.Transform(projection, view); shader.setVec3("lightPos", glm::vec3(0.7, 0.2, 0.5)); shader.setVec3("viewPos", camera.Position); displayChunk(shader, vox, &chunks, frustum); glDepthFunc(GL_LEQUAL); // change depth function so depth test passes when values are equal to depth buffer's content skyboxShader.use(); view = glm::mat4(glm::mat3(camera.GetViewMatrix())); // remove translation from the view matrix skyboxShader.setMat4("view", view); skyboxShader.setMat4("projection", projection); // skybox cube glBindVertexArray(skybox.skyboxVAO); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_CUBE_MAP, skybox.cubemapTexture); glDrawArrays(GL_TRIANGLES, 0, 36); glBindVertexArray(0); glDepthFunc(GL_LESS); // set depth function back to default glfwSwapBuffers(window); glfwPollEvents(); for (unsigned i = 0; i < 1; ++i) { threads[i] = std::thread([&mtx, i] { { // Use a lexical scope and lock_guard to safely lock the mutex only for // the duration of std::cout usage. std::lock_guard<std::mutex> iolock(mtx); std::cout << "Thread #" << i << " is running\n"; } }); } for (auto &t : threads) { t.join(); } }
Threads and processes are basically the same thing under Linux, both are created by calling clone() internally. So you can see that a thread is not something cheap to create and you are doing it several times inside each loop! Don't beat yourself for that, the first generations of web servers (Apache) were like that too, for each connection they spawned a process or thread. With time they realized that just the creation of the process/thread was where the majority of the time was being spent. Creating a process or thread can take several milliseconds. The next evolution came with thread pools and that's what I suggest you do. What you should do is to create all the threads upfront and lock them with a mutex and condition variable. When you have work for them to do, you push the data into their queue or object and fire the condition variable, which will unlock the mutex and release the thread. This will typically cost you just 3-10 microseconds, which is a thousand times better than what you have right now. You can write your own thread pool as in this tutorial or ou can use a predefined pool as the one provided by boost::thread_pool. If you even find that 3-10 microseconds is too much, you can have your threads spinning at 100% cpu and use a lock free container like the boost spsc container to communicate. The latency between threads in this case drops to a few dozen nanoseconds. The downside of this approach is that your threads will always be consuming 100% of one core even when doing nothing.
69,473,896
69,474,526
How do I format an bluetooth address as a btaddr?
I have a bluetooth address (7C9EBD4CBFB2) that I need to connect to using winsock. This is my code, which returns error as -1, and won't connect to my device. #include <winsock2.h> #include <ws2bth.h> #pragma comment(lib, "Ws2_32.lib") #include <Windows.h> #include <iostream> using namespace std; SOCKADDR_BTH sockAddr; SOCKET btSocket; int error; int main() { btSocket = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM); memset(&sockAddr, 0, sizeof(sockAddr)); sockAddr.addressFamily = AF_BTH; sockAddr.serviceClassId = RFCOMM_PROTOCOL_UUID; sockAddr.port = BT_PORT_ANY; sockAddr.btAddr = 0x7C9EBD4CBFB2; error = connect(btSocket, (SOCKADDR*)&sockAddr, sizeof(sockAddr)); cout << error; } How do I format this to use as a btaddr? Thanks..
You are not calling WSAStartup() before socket(). You would have realized this sooner if you had been doing better error checking. See Handling Winsock Errors. socket() would have returned INVALID_SOCKET (-1), and then WSAGetLastError() would have returned WSANOTINITIALISED (10093). Successful WSAStartup not yet performed. Either the application has not called WSAStartup or WSAStartup failed. The application may be accessing a socket that the current active task does not own (that is, trying to share a socket between tasks), or WSACleanup has been called too many times. And then connect() would have failed with SOCKET_ERROR (-1), and WSAGetLastError() would have returned WSAENOTSOCK (10038). Socket operation on nonsocket. An operation was attempted on something that is not a socket. Either the socket handle parameter did not reference a valid socket, or for select, a member of an fd_set was not valid. Per the Bluetooth Programming with Windows Sockets documentation: As with all Windows Sockets application programming, the WSAStartup function must be called to initiate Windows Sockets functionality and enable Bluetooth. ALWAYS check error codes on system calls! Try something more like this: #include <winsock2.h> #include <ws2bth.h> #include <Windows.h> #include <iostream> #include <cstdio> #pragma comment(lib, "Ws2_32.lib") int str2ba(const char *straddr, BTH_ADDR *btaddr) { int i; unsigned int aaddr[6]; BTH_ADDR tmpaddr = 0; if (std::sscanf(straddr, "%02x:%02x:%02x:%02x:%02x:%02x", &aaddr[0], &aaddr[1], &aaddr[2], &aaddr[3], &aaddr[4], &aaddr[5]) != 6) return 1; *btaddr = 0; for (i = 0; i < 6; i++) { tmpaddr = (BTH_ADDR) (aaddr[i] & 0xff); *btaddr = ((*btaddr) << 8) + tmpaddr; } return 0; } int main() { WSADATA wsa; memset(&wsa, 0, sizeof(wsa)); int error = WSAStartup(MAKEWORD(2,2), &wsa); if (error != 0) { std::cerr << "WSAStartup() failed, error: " << error; return -1; } SOCKET btSocket = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM); if (btSocket == INVALID_SOCKET) { error = WSAGetLastError(); std::cerr << "socket() failed, error: " << error; WSACleanup(); return -1; } SOCKADDR_BTH sockAddr; memset(&sockAddr, 0, sizeof(sockAddr)); sockAddr.addressFamily = AF_BTH; sockAddr.serviceClassId = RFCOMM_PROTOCOL_UUID; sockAddr.port = BT_PORT_ANY; str2ba("7C:9E:BD:4C:BF:B2", &sockAddr.btAddr); if (connect(btSocket, (SOCKADDR*)&sockAddr, sizeof(sockAddr)) == SOCKET_ERROR) { error = WSAGetLastError(); std::cerr << "connect() failed, error: " << error; closesocket(btSocket); WSACleanup(); return -1; } // use btSocket as needed... closesocket(btSocket); return 0; }
69,474,540
69,474,559
Is it possible to make a C++ function for a data type that is accessible using a dot operator?
I want to make a function associated to a data type say int that can be accessed using the dot operator such that: int x = 9; std::string s = x.ToString(); I know how to do so with std::string and the likes but not the int data type. Is that possible?
No, this is not possible. An int is a primitive type whereas a std::string is a class type that contains methods. However, you could create your own struct/class in order to implement this functionality. The struct Int type has a constructor which takes in an integer and uses an initializer list :a(value) to assign the internal integer with a given value. #include <string> struct Int { int a; Int(int value) : a(value) {} std::string ToString() const { return std::to_string(a); } }; int main() { Int a = 20; std::string s = a.ToString(); }
69,474,794
69,475,049
Prime factors with stack implementation in C++
Greetings stack overflow, recently run into a problem where my code isn't doing exactly what I intend it to do. My intentions are for the user to input a number and then the program will check for its prime factors, when it finds a prime factor I want it to push the number into a stack. I've tried putting cout statements throughout the program to see if any specific spot isn't working but I haven't found anything yet. I believe I am very close to figuring this out, but I am not sure how to advance from here. Here is my code: #include <iostream> #include <cmath> using namespace std; class stack { public: static const int MAX = 100; stack() { used = 0; } // constructor void push(int entry); int pop(); int size() { return used; } bool empty() { return used == 0;} private: int data[MAX]; int used; // how many elements are used in the stack, top element is used - 1 }; void stack::push(int entry) { data[used] = entry; ++used; } int stack::pop() { --used; return data[used]; } void primeFactors(stack, int); int main() { stack primeValues; int entry = 0; cout << "Enter a positive integer (0 to stop): "; cin >> entry; if (entry != 0) { cout << "Prime factors: " << entry << " = "; } primeFactors(primeValues, entry); while(primeValues.pop() != 0) // hopefully continues to pop the prime factors until it reaches zero? { cout << primeValues.pop() << " "; } return 0; } void primeFactors(stack primeValues, int entry) { if (entry == 0) { return; // terminate when zero is reached } if (entry == 1) { cout << entry; // if 1 is reached display one } while (entry % 2 == 0) // while there is no remainder do the following { primeValues.push(2); // push two into stack entry = entry/2; } for (int i = 3; i <= sqrt(entry); i = i+2) // start looping through numbers to find more prime factors { while (entry % i == 0) { primeValues.push(i); entry = entry/i; } } if (entry > 2) // if the number is greater than two and doesnt have prime factors push the number { primeValues.push(entry); } } I've tried all sorts of different numbers and nothing seems to work. I've tried just popping a few times to see if anything was pushed, but it only displayed zero. What am I missing here?
You've made a very simple error. In passing your stack by value to primeFactors the stack is copied and the copy worked on. When primeFactors finishes, that copy is discarded, and your original empty stack is left. Taking advantage of C++ templates: #include <iostream> #include <cmath> template <typename T, unsigned int MAX> class stack { private: T data[MAX] = { 0 }; unsigned int used = 0; public: stack() : used(0) {} void push(T entry) { if (used <= MAX - 1) { data[used] = entry; used += 1; } } T pop() { used -= 1; return data[used]; } unsigned int size() const { return used; } bool empty() const { return used == 0; } }; template <typename T, unsigned int MAX> void primeFactors(stack<T, MAX>&, int); int main() { stack<int, 100> primeValues; int entry = 0; std::cout << "Enter a positive integer (0 to stop): "; std::cin >> entry; if (entry == 0) { return 0; } primeFactors(primeValues, entry); while (!primeValues.empty()) { std::cout << primeValues.pop() << " "; } std::cout << std::endl; } template <typename T, unsigned int MAX> void primeFactors(stack<T, MAX>& primeValues, int entry) { if (entry == 0) { return; } if (entry == 1) { std::cout << entry << std::endl; } while (entry % 2 == 0) { primeValues.push(2); entry /= 2; } for (int i = 3; i <= std::sqrt(entry); i += 2) { while (entry % i == 0) { primeValues.push(i); entry /= i; } } }```
69,475,015
69,486,620
ncursesw causing weird behaviour
On WSL2, I'm using the first example code given in this tutorial website: https://tldp.org/HOWTO/NCURSES-Programming-HOWTO/panels.html. Code: #include <panel.h> int main() { WINDOW *my_wins[3]; PANEL *my_panels[3]; int lines = 10, cols = 40, y = 2, x = 4, i; initscr(); cbreak(); noecho(); /* Create windows for the panels */ my_wins[0] = newwin(lines, cols, y, x); my_wins[1] = newwin(lines, cols, y + 1, x + 5); my_wins[2] = newwin(lines, cols, y + 2, x + 10); /* * Create borders around the windows so that you can see the effect * of panels */ for(i = 0; i < 3; ++i) box(my_wins[i], 0, 0); /* Attach a panel to each window */ /* Order is bottom up */ my_panels[0] = new_panel(my_wins[0]); /* Push 0, order: stdscr-0 */ my_panels[1] = new_panel(my_wins[1]); /* Push 1, order: stdscr-0-1 */ my_panels[2] = new_panel(my_wins[2]); /* Push 2, order: stdscr-0-1-2 */ /* Update the stacking order. 2nd panel will be on top */ update_panels(); /* Show it on the screen */ doupdate(); getch(); endwin(); } When I run the code with the flags -lpanel -ncurses, it works fine as shown below: When I run the code with the flags -lpanel -ncursesw, it doesn't work well:
The example shows two problems: mixing -lpanel with -lncursesw (won't work because the size of the types holding character plus attributes differs). You should use -lpanelw. there's no call to setlocale to make line-drawing work portably.
69,475,135
69,475,253
Access a vector or an array from another file in C++
I'm trying to access the elements of an array/vector from another file (pattern.cpp here). According to this discussion (http://cplusplus.com/forum/beginner/183828/) I should do //pattern.cpp namespace myprogram { void Pattern::FromReal() { extern std::vector<double> real_data; for (auto it=real_data.begin(); it !=real_data.end(); it++) std::cout<<" my vector "<< *it <<" "; } } and the vector is here //RealData.cpp #include <vector> std::vector<double> real_data{ 0., 0., 1.46, 1.51, 1.55, 1.58, 1.45, 1.48, 1.54, 1.54, 1.60, 1.56}; When I compile I get this error <directory>/x86_64/Gcc/gcc620_x86_64_slc6/6.2.0/x86_64-slc6/include/c++/6.2.0/bits/stl_iterator.h:770: undefined reference to `myprogram::real_data' collect2: error: ld returned 1 exit status And I use CMake and RealData.cpp is already added to CMakeList. What is wrong here? What should I change?
Here is the working example. Just create(if not already) a realdata.h file which have the extern for the real_data vector. Then you can just include this header in pattern.cpp and wherever you want this real_data vector like in main.cpp . main.cpp #include <iostream> #include "pattern.h" #include "realdata.h" extern std::vector<double> real_data; int main() { std::cout<<"Size of vector from other file is: "<<real_data.size()<<std::endl; myprogram::Pattern obj; obj.FromReal(); return 0; } pattern.h #ifndef PATTERN_H #define PATTERN_H namespace myprogram { class Pattern { public: void FromReal(); }; } #endif pattern.cpp #include "pattern.h" #include "realdata.h" #include <iostream> namespace myprogram{ void Pattern::FromReal() { for (auto it=real_data.begin(); it !=real_data.end(); it++) std::cout<<" my vector "<< *it <<" "<<std::endl; } } realdata.h #ifndef REALDATA_H #define REALDATA_H #include<vector> extern std::vector<double> real_data; #endif realdata.cpp #include "realdata.h" std::vector<double> real_data{ 0., 0., 1.46, 1.51, 1.55, 1.58, 1.45, 1.48, 1.54, 1.54, 1.60, 1.56}; Also don't forget to use header guards
69,475,322
69,483,295
Cumulative sum with array in C++
#include <iostream> #include <ctime> #include <cstdlib> #include <cmath> #include <fstream> #include <iomanip> #include <sstream> using namespace std; int iData, tData; void randgen(int max, int min){ srand((unsigned) time(0)); } int main() { cout << "Masukkan jumlah data: "; cin >> iData; int jData[iData], randNum[iData], fProb[iData]; double probkei[iData], tKumul[iData],tepiA[iData], tepiB[iData]; int tData; for(int i=1; i<=iData; i++){ cout << "Masukkan data ke-" << i << ": "; cin >> jData[i]; tData += jData[i]; //jumlahkan seluruh data untuk mencari probabilitas tiap variabel }system("cls"); probkei[0]=0; cout << setw(10) << "Data ke" << setw(10) << "Frekuensi" << setw(15) << "Probabilitas" << setw(20) << "Kumulatif" << setw(10) << "Interval" << endl; for(int i=0; i<iData; i++){ probkei[i] = (double) jData[i]/tData; //typecast integer to double for the probability if(jData[i]==jData[1]){ tKumul[i] = probkei[i]; }else if(i<i+i){ tKumul[i] = probkei[i] + probkei[i+1]; //for cumulative sum 1 way } probkei[i] = round(probkei[i] * 1000.0) / 1000.0; //rounding the probability tKumul[i] = round(tKumul[i] * 1000.0) / 1000.0; cout << setw(10) << i+1 << setw(10) << jData[i] << setw(15) << probkei[i] << setw(20); int temp; cout<<"data "<<probkei[i]+probkei[i+1]; //for cumulative sum 2 way cout << setw(10) << tKumul[i] << endl; /*if (i == iData || jData[i] != jData[i - 1]) { temp += count; cout << "Cumulative frequency of " << jData[i - 1] << " in the array is: " << temp << endl; count = 1; }else{ count++; }*/ } cout << setw(20) << "Total data: " << tData << endl; return 0; } I want to count cumulative frequency from my array data. First is entering the value/total of the number of data in the array. Next is entering the value for each data one by one and then counting all probabilities of each data(the possibilities are declared in double). And then counting the cumulative which is sum the n data with the n+1 data. And the last is making the top and bottom edges for each data to be used as a random number interval. I've done my best and finding the solution but I still confused why it's doesn't work. I was trying to count it in 2 ways but all of them do nothing. This is a Monte Carlo Simulation. example Table
This: int iData; cin >> iData; int jData[iData]; is using variable-length arrays, which are not standard C++. Rather use std::vector instead: int iData; cin >> iData; std::vector<int> jData(iData); The tData local variable is uninitialized: int tData; ... tData += jData[i]; It should be initialized to 0. The condition i<i+i doesn't make sense. There is something weird going on with the indexes. The input is loaded from index 1 but the second loop starts from 0. This loading from 1 is also not accounted in size of the arrays, so the last element will overflow the array. There is something wrong with this too: tKumul[i] = probkei[i] + probkei[i+1]; If this is supposed to be cumulative sum then tKumul should appear on the right side too. If we load data from 0, then the second loop should look like this: for (int i = 0; i < iData; i++) { probkei[i] = (double) jData[i] / tData; if (i == 0) { tKumul[i] = probkei[i]; } else { tKumul[i] = probkei[i] + tKumul[i-1]; } With this code (see godbolt) the output is: Data ke Frekuensi Probabilitas Kumulatif 1 5 0.067 0.067 2 10 0.133 0.2 3 15 0.2 0.4 4 20 0.267 0.667 5 25 0.333 1 Total data: 75 In addition I would suggest using fixed and setprecision(3) instead of manual rounding: cout << fixed << setprecision(3); and using algorithms instead of loops. Calculating probabilities can be replaced by std::transform and calculating cumulative sum can be replaced by std::partial_sum: std::transform( jData.begin(), jData.end(), probkei.begin(), [tData](auto elem) { return (double) elem / tData; } ); std::partial_sum(probkei.begin(), probkei.end(), tKumul.begin()); With this code (see godbolt) the output is: Data ke Frekuensi Probabilitas Kumulatif 1 5 0.067 0.067 2 10 0.133 0.200 3 15 0.200 0.400 4 20 0.267 0.667 5 25 0.333 1.000 Total data: 75
69,475,384
69,475,888
Finding the intersection of two binary search trees
I am building and returning a new binary search tree constructed of the intersection of two other binary search trees. I have available to me a find function which I am using to check if any values of the first tree are found in the second tree and if they are I insert them into a new tree. My issue is that the new tree "res" does not update upon recursion. So if I test it with 8, 4, 10 for tree1 and tree2 is 8, 6, 4, 13 my new tree only contains 8 and not 8 and 4. Grateful for any feedback! BinSearchTree *BinSearchTree::intersectWith(TreeNode *root1, TreeNode *root2) { BinSearchTree *res = new BinSearchTree(); //traverse one tree and use find to traverse the second tree if(local_find(root2, root1->value()) && !local_find(res->root, root1->value())) res->insert(root1->value()); if(root1->leftSubtree() != nullptr) intersectWith(root1->leftSubtree(), root2); if(root1->rightSubtree() != nullptr) intersectWith(root1->rightSubtree(), root2); return res; }
You are overwriting res every time you call intersectWith() by calling 'new BinSearchTree()'. To fix this, create res outside of interSectWith() and then pass it in as a third parameter. (You could then also consider making intersectWith() return void, as a return value is no longer needed.)
69,475,538
69,476,078
How to detect selection of shapes in OpenCASCADE?
I am using OPENCASCADE 3D library together with Qt. I have set up 3D display, and displayed several items of TopoDS_Shape in a window, using calls to AIS_InteractiveContext::Display method. Now I'd like to have some event processing when user picks a shape on 3D display. I have checked documentation to AIS_InteractiveContext ( https://dev.opencascade.org/doc/refman/html/class_a_i_s___interactive_context.html ). There is a way to query items in 3D view. But it can only QUERY the selection: SelectedShape method (https://dev.opencascade.org/doc/refman/html/class_a_i_s___interactive_context.html#ac7879e85fade79a71e4f543a154763ff) IsSelected method for graphical representation Selection method Constantly querying AIS_Interactive context for selection changes is not a way. Is there any way to setup callback in opencascade when selection was changed?
No, you should react on mouse clicks or key strokes to check whether the user wants to select something. There is an Open CASCADE Qt sample called "Tutorial", you might want to check it. In the file ".../samples/qt/Common/src/View.cxx" you can find a sample implementation.
69,475,710
69,476,000
Simple Encryption program array
Building a simple program that multiplies the ASCII value of chars in a string by 3 to encrypt and then divide by 3 to decrypt. So far I got the encryption part down but whenever I enter what the encryption gave and try to decrypt it doesn't work. I think it has something to do with the buffer stream but I could be wrong if anyone could help. #include<iostream> using namespace std; int main() { string message; int charValue; int counter; int encrypt; char choice; char quit = 'N'; while (quit == 'N') { cout << "Enter E to encrypt or D to Decrypt\n"; cin >> choice; toupper(choice); cout << "Enter text no spaces: "; cin >> message; int messagelen = message.length(); string stringArray[255]; if (choice == 'E') { for (counter = 0; counter < messagelen; counter++) //*3 to ascii val { stringArray[counter] = message[counter] * 3; } for (counter = 0; counter < messagelen; counter++) { cout << stringArray[counter]; } } else { for (counter = 0; counter < messagelen; counter++) // divide 3 to ascii val { stringArray[counter] = message[counter] / 3; } for (counter = 0; counter < messagelen; counter++) { cout << stringArray[counter]; } } cout << "\nY to go again N to quit"; cin >> quit; } return 0; }
This is a working implementation, although I agree with the other answer that you should use encrypt and decrypt functions. I found quite a few other bugs with your code working through it. You should enable all warnings with -Wall -Werror and fix them: #include <iostream> #include <vector> #include <sstream> int main() { // removed some unused variables std::string message; size_t counter; char choice; char quit; // use vector of int instead of array of strings std::vector<int> encryptArray; // change to do while loop. Not particularly necessary, but I think // it makes more sense in this case. Your condition is broken. If the // user enters 'Y' at the end to go again, then the quit == 'N' // condition is false and the program terminates. do { std::cout << "Enter E to encrypt or D to Decrypt\n"; std::cin >> choice; // toupper returns a value, you need to assign it to choice. // Not capturing the return value makes this a noop. choice = toupper(choice); if (choice == 'E') { std::cout << "Enter text no spaces: "; std::cin >> message; size_t messagelen = message.length(); // initialize vector to input message length size encryptArray = std::vector<int>(messagelen); for (counter = 0; counter < messagelen; counter++) //*3 to ascii val { encryptArray[counter] = message[counter] * 3; } // Note, this 2nd loop is more work than you need, you could // simply put the std::cout line in the loop above below the // assignment for (counter = 0; counter < messagelen; counter++) { // added the separator just for clarity. You could also print // hex bytes std::cout << encryptArray[counter] << "|"; } } else { // all the data we care about is in the vector now for (counter = 0; counter < encryptArray.size(); counter++) // divide 3 to ascii val { // you don't want to /3 what's in the message here, you want // to /3 the encrypted values, which are in the vector encryptArray[counter] = encryptArray[counter] / 3; } // plenty of ways to convert the vector to a string, this is not // a "modern" way. // Note, you could skip this loop entirely, and in the one // above, simply do ss << (char)(encryptArray[i] / 3); // Not necessary to write the data back to encryptArray first. std::stringstream ss; for (size_t i=0; i<encryptArray.size(); ++i) { ss << (char)encryptArray[i]; } std::cout << "decrypted string: " << ss.str() << std::endl; } std::cout << "\nY to go again N to quit: "; std::cin >> quit; } while(quit != 'N'); // loop until quit == N return 0; } Finally, I removed using namespace std;, here's why Things get squirrely working with stdin on godbolt, but here's a working demonstration, at least initially.
69,476,112
69,476,525
Abstract class init in the initialization list
I want to understand the following c++ concept. class_a is abstract class and as per abstract class concept we cannot create any instance of it. i have used the initlization list and abstract class as well but never used following concept. In the code ,the initlization list of class_b, class_a is initlized. I want to understand what is meaning of initlizing it in the initilization list. class_b::class_b(int val):nameA::class_a() in fileA.cpp namespace nameA { class class_a { public: virtual ~class_a(){}; virtual void process()=0; }; } in fileb.h file namespace nameB { class class_b : public nameA::class_a { public: class_b(int val); } } in fileb.cpp file namespace nameB { class_b::class_b(int val) :nameA::class_a() //Want to understand this line... }
It would be more clear with a slightly richer example. Because if the abstract base class has neither attributes nor methods it is harder to see how it can be initialized. class NamedProcessor { std::string name; // a private attribute public: NamedProcessor(const std::string &name) : name(name) {} virtual ~NamedProcessor() {} // a pure virtual method to make the class abstract virtual void process() = 0; std::string getName() { return name; } }; class Doubler : public NamedProcessor { int value; // a private attribute public: Doubler(int initial = 1) : NamedProcessor("Doubler") { reset(initial); } void reset(int initial) { value = initial; } int getValue() { return value; } // the concrete implementation void process() { value *= 2; } }; int main() { // Compiler would croak witherror : variable type 'NamedProcessor' is an abstract class // NamedProcessor wrong("Ill formed"); Doubler doubler; std::cout << doubler.getName() << "\n"; // name has been initialized... return 0; } Here the abstract class holds an attribute which will be available to subclasses. And this attribute has to be set at construction time because there is no public setter for it. The language has to provide a way to initialize the abstract subclass, meaning not building an object, but initializing a sub-object - here setting the name.
69,476,158
69,481,115
I am getting segmentation fault while using Morris algorithm for inorder traversal of a binary tree
The question link was this: Inorder Traversal (GFG) I referred the geeksforgeeks article that had the same code but in void function. I modified it to fit the question. Now I am getting segmentaion fault and I don't know why. The GFG article: Inorder Tree Traversal without recursion and without stack! vector<int> inOrder(Node* root) { // Your code here vector<int>ans; Node* current = root; Node* pre; if(!root){return ans;} while(current){ if(!root->left){ ans.push_back(current->data); current = current->right; } else{ pre = current->left; while(pre->right && (pre->right != current)){pre = pre->right;} if(!pre->right){ pre->right = current; current = current->left; } else{ pre->right = NULL; ans.push_back(current->data); current = current->right; } } } return ans; }
The following condition is wrong: if(!root->left){ This will make the same check in each iteration. It should relate to the current node: if(!current->left){
69,476,464
69,476,734
How can I replicate compile time hex string interpretation at run time!? c++
In my code the following line gives me data that performs the task its meant for: const char *key = "\xf1`\xf8\a\\\x9cT\x82z\x18\x5\xb9\xbc\x80\xca\x15"; The problem is that it gets converted at compile time according to rules that I don't fully understand. How does "\x" work in a String? What I'd like to do is to get the same result but from a string exactly like that fed in at run time. I have tried a lot of things and looked for answers but none that match closely enough for me to be able to apply. I understand that \x denotes a hex number. But I don't know in which form that gets 'baked out' by the compiler (gcc). What does that ` translate into? Does the "\a" do something similar to "\x"?
This is indeed provided by the compiler, but this part is not member of the standard library. That means that you are left with 3 ways: dynamically write a C++ source file containing the string, and writing it on its standard output. Compile it and (providing popen is available) execute it from your main program and read its input. Pretty ugly isn't it... use the source of an existing compiler, or directly its internal libraries. Clang is probably a good starting point because it has been designed to be modular. But it could require a good amount of work to find where that damned specific point is coded and how to use that... just mimic what the compiler does, and write your own parser by hand. It is not that hard, and will learn you why tests are useful... If it was not clear until here, I strongly urge you to use the third way ;-)
69,476,676
69,476,808
arguments a constant in template function
I have a template function as below which has one of the arguments a constant template<typename T> T maxAmong( T x, const T y) { return x ; } For explicit specialization I expected to have the below code. But this gives a compile error. template<> char* maxAmong( char* x, const char* y) { return x; } Whereas the making both return type and both arguments const works template<> const char* maxAmong( const char* x, const char* y) { return x; } Why does the code in second snippet fail as for me the code looks more right that way.
const char * is a pointer to a const char. char * const is a constant pointer to a char. Thus, your template specialization should look like this: template<typename T> T maxAmong( T x, const T y) { return x ; } template<> char* maxAmong( char* x, char* const y) { return x; } This thread might be helpful as well. What is the difference between char * const and const char *?
69,476,849
69,476,992
Can you extract bitmask directly from bitfield in C++?
Considering following example: #include <iostream> using namespace std; struct Test { uint8_t A:1; uint8_t B:1; uint8_t C:1; uint8_t D:1; }; int main() { Test test; test.A = 1; test.B = 0; test.C = 1; test.D = 0; int bitmask = test.A | (test.B << 1) | (test.C << 2) | (test.D << 3); cout << "Size: " << sizeof(test) << ", bitmask: " << bitmask; return 0; } I'm assuming that the data in the bitfield is represented as bitmask somehow? I was wondering if there is a way to get a bitmask directly, without having to go through and shift all members. In this case it's not a big deal, but if you have large bitfield it can get pretty tedious. For example it would be great if I could do something like this: int bitmask = (int)test; Of course that doesn't work. Any way to achieve similar robustness?
Assuming you want to convert the entire struct, and there exists an integral type with the same size as the struct: Test test; test.A = 1; test.B = 0; test.C = 1; test.D = 0; cout << (int)std::bit_cast<char>(test) << '\n'; std::bit_cast is a C++20 feature. char is used here because it has the same size as Test. I'm casting the result to int, because otherwise cout interpretes the resulting number as a character code. The alternative solution is to memcpy the struct (or a part of it) to an integer: char ch; std::memcpy(&ch, &test, 1); cout << (int)ch << '\n'; Unlike bit_cast, this doesn't require a modern compiler, and allows you to inspect a specific part of the struct (assuming the part is byte-aligned).
69,476,900
69,477,013
In this Linked List why it is not allowing me to run again and create another node what is the error in my code?
I am trying to make employee database using Linked list data structure but once I enter the value the option to run again is not available and also display function is not executes code stops before that I have checked the code sevearl times but I am not able to spot the error. #include<iostream> using namespace std; class node { public: int Emp_No; node *next; node() { next=NULL; } }; class Link_List { public: node *head; Link_List() { head==NULL; } void create(); void display(); }; void Link_List::create() { node *temp,*p; int again; do { temp=new node(); cout<<"Enter Employee No.: "; cin>>temp->Emp_No; if (head==NULL) { head=temp; } else { p=head; while (p->next!=NULL) { p=p ->next; } p ->next=temp; } cout<<"Enter 1 to add more: "; cin>>again; } while (again==1); } void Link_List::display() { node *p1; if (head==NULL) { cout<<"The linked list is empty"<<endl; } else { p1=head; while (p1!=NULL) { cout<<"Employee No:"<<p1 ->Emp_No<<endl; p1=p1->next; } } } int main() { Link_List emp1; emp1.create(); emp1.display(); return 0; } Following is the output it just allows me to enter the value once then wothout asking for next it ends and also display function is also not executed here: PS E:\Programming\C++> cd "e:\Programming\C++\" ; if ($?) { g++ Linked_List.cpp -o Linked_List } ; if ($?) { .\Linked_List } Enter Employee No.: 101 PS E:\Programming\C++>
You got a typo in Link_List constructor. it should be: head=NULL; not head==NULL; It seems to work after replacement. TIP: Although statically scanning code with your eyes makes you think better; A debugger is an essential tool you need to adopt.
69,477,385
69,477,865
Can dangling pointer be equal to valid pointer during constant evaluation in C++?
During constant expression evaluation in C++17, shall the compiler consider any pointer addressing a valid object unequal to any pointer addressing an object after the end of its lifetime? For example: constexpr auto f(int * x = nullptr) { int c = 0; auto p = &c; if ( x == p ) throw "unexpected"; return p; }; int main() { static_assert( f( f() ) ); } Here the inner call of function f() returns a dangling pointer, which is passed to f again. I believed that the condition x == p must be false since x is a dangling pointer and p is a valid pointer, and it is indeed so in Clang. But in GCC the condition is satisfied and the constant evaluation fails due to throw. Demo: https://gcc.godbolt.org/z/ehcMro17q Is it an undefined or implementation-defined behavior, or one of the compilers is wrong?
The result of comparing a dangling pointer with any other pointer is implementation-defined: When the end of the duration of a region of storage is reached, the values of all pointers representing the address of any part of that region of storage become invalid pointer values. […] Any other use of an invalid pointer value has implementation-defined behavior. ([basic.stc]/4) (equality comparison is included in “other use” here.) As noted in the comments, even the lvalue-to-rvalue conversion of the comparison operands invokes implementation-defined behaviour for the invalid pointer ([conv.lval]/3.3). Unfortunately I can’t find anything that mandates lvalue-to-rvalue conversion for the operands of an equality comparison; [expr.eq]/2 at best implies this very indirectly.
69,477,518
69,486,588
how to use and update panels in ncursesw
I'm currently coding in C++ in Ubuntu WSL2, using the <panel.h> header to create panels in ncursesw, as I need Unicode characters. I've done a couple tests already, where the results are shown in the table below: This is the code and result when creating a window with a WINDOW* and -lncursesw. Code: #include <panel.h> int main() { setlocale(LC_ALL, ""); initscr(); noecho(); cbreak(); refresh(); WINDOW *window {newwin(0, 0, 0, 0)}; box(window, 0, 0); mvwaddstr(window, 1, 1, "\U0001F600"); wrefresh(window); getch(); endwin(); } Result: This is the code and result when creating a window with a PANEL* and -lncursesw. Code: int main() { setlocale(LC_ALL, ""); initscr(); noecho(); cbreak(); PANEL *panel {new_panel(newwin(0, 0, 0, 0))}; box(panel_window(panel), 0, 0); mvwaddstr(panel_window(panel), 1, 1, "\U0001F600"); // wrefresh(panel_window(panel)); update_panels(); doupdate(); getch(); endwin(); } Result: However if I uncomment the wrefresh() line, I get the same desired result when using WINDOW *. Why is this happening?
doupdate doesn't do a wrefresh (it's generally used after one more more windows is prepared using wnoutrefresh). Without an explicit wrefresh, your program is getting the wrefresh done as a side-effect of getch — which refreshes stdscr, but that in turn has only the pending werase from initscr followed by the box call: it seems you'll get an empty box.
69,477,605
69,478,853
Running 'grep' command using exec functions
I am trying to run grep command using execvp. I have to save the output into an output file like output.txt. The code, I have tried is given below: #include<iostream> #include<unistd.h> #include<stdio.h> #include<stdlib.h> #include<sys/types.h> #include<sys/wait.h> using namespace std; int main(){ pid_t pid = fork(); int status = 0; char* args[] = {"grep", "-n", "out", "*", ">", "output.txt", NULL}; //char* args[] = {"out", "/os_lab/assign_01/*", "/usr", NULL}; if(pid == 0){ cout<<"I am Child Process\n"; status = 2; execvp("grep", args); } else if(pid > 0){ cout<<"I am Parent Process\n"; wait(&status); } else{ cout<<"Error in system call\n"; } return 0; } When I run this code, the output on the terminal is as follows: I am Parent Process I am Child Process grep: *: No such file or directory grep: >: No such file or directory
The execvp() function calls directly the program and execute it with the provided arguments. The use of wildcards like * are provided by the shell terminal, so the grep is understanding the * as a file to be grep'ed. If you want to call the grap using wildcards and the operator > you should use the function system() on C++. The following code should work: #include<iostream> #include<unistd.h> #include<stdio.h> #include<stdlib.h> #include<sys/types.h> #include<sys/wait.h> using namespace std; int main(){ pid_t pid = fork(); int status = 0; //char* args[] = {"grep", "-n", "out", "*", ">", "output.txt", NULL}; //char* args[] = {"out", "/os_lab/assign_01/*", "/usr", NULL}; if(pid == 0){ cout<<"I am Child Process\n"; status = 2; //execvp("grep", args); system("grep -n out * > output.txt"); } else if(pid > 0){ cout<<"I am Parent Process\n"; wait(&status); } else{ cout<<"Error in system call\n"; } return 0; }
69,477,812
69,478,223
Is there a way to read the function parameter as the exact name passed in c++?
For my program (C++), I need to read one of the function parameter as it is given while calling the function, for example: void foo(int arg) { // I need to read the "arg" parameter here, not its value but the exact thing passed while calling the "foo" function } for example: int bar = 10; foo(bar); // I want to read "bar" string Is there a way to do that? One of the alternate option I can see is make two parameters and call the function like: foo(bar, "bar"); I'm a beginner in c++, so it may be a silly question...
AS there is no build-in reflection in C++, in resulting code all ids will be gone. But you can emulate it by using stringize operator #, if you don't mind to use some wrappers. assert() macro in some implementations makes use of it. #include <iostream> void order(int arg1, int arg2, const char* str) { std::cout << str << arg1*arg2 << std::endl; } #define REFLECT_INVOKE(func, ...) (func)(__VA_ARGS__, #func "(" #__VA_ARGS__ ") = ") int main() { int x = 6; int y = 11; REFLECT_INVOKE(order,x,y); } Output: order(x,y) = 66 Operator # literally wraps following token in quotes before placing result into processed source before compilation, so statement REFLECT_INVOKE(order,x,y); is processed into (order)(x,y,"order" "(" "x,y" ") = "); We can make it a bit more universal, using new features (there is probably simple and obvious way to do this): int order(int arg1, int arg2) { return arg1*arg2; } template<class F, class ...Args> auto debug_call( F func, const char* str, Args... args) -> decltype(std::forward<F>(func)(std::forward<Args>(args)...)) { if constexpr ( std::is_same<decltype(std::forward<F>(func)(std::forward<Args>(args)...)),void>::value) { std::cout << str; func(args...); } else { auto res = func(args...); std::cout << str << "= " << res; return res; } } #define REFLECT_INVOKE(func, ...) (debug_call)(func, #func "(" #__VA_ARGS__ ") ", __VA_ARGS__) int main() { int x = 6; int y = 11; REFLECT_INVOKE(order,x,y); } This is barely usable outside of debugging purposes.
69,478,685
69,478,993
Declare a C++ std::list with elements that point to other elements in the list
I'm trying to use an std::list and an std::unordered_map to store a directed acyclic graph. Each list element stores a node key (unsigned) and its children. And the map stores, for each key, an iterator to the node in the list: std::list<std::pair<unsigned, std::list<decltype(lst.begin())>>> lst; std::unordered_map<unsigned, decltype(lst.begin())> nodemap; But decltype(lst.begin()) in the declaration of lst results in a compile error since lst is not defined yet. Can I define lst another way ? Edit: using std::vector<unsigned, std::list<unsigned>> vec would probably work, where list<unsigned> contains indexes into vec. Not sure whether sticking with the initial std::list is better or worse.
Write classes. Within the definition of the class, it is an incomplete type, which means you can use pointers (or references) to it. The children pointers can be non-owning, with the map owning all the nodes. class Graph { struct Node { unsigned key; std::vector<Node *> children; }; std::unordered_map<unsigned, Node> nodes; public: // graph behaviours };
69,478,707
69,478,883
Default parameters and forward declaration
I have a class Property with a constructor in which I want default parameters, in a file property.h: class Property { Property(OtherClass* value = myApp->someValue) {...}; }; where myApp, of another type Application, is defined in another file that makes extensive use of this Property class. Since this other file #includes property.h, of course, I cannot #include this file in property.h property.h does not know about myApp nor Application (though property.cpp does, and OtherClass is known in property.h). I could forward declare OtherClass and declare myApp as extern, but this results in an error C2027 "use of undefined type Application", as expected : class Application; extern Application* myApp; class Property { Property(OtherClass* value = myApp->someValue) {...}; }; A solution could be to have the default parameter in the .cpp file, but this is not advisable (here). How can I get this default parameter working ? (i.e., not another solution that would involve not having default parameters telling me default parameters are evil, or that my design is poor to start with etc. ;) ). Thanks!
The remarkable point is that the default argument of function parameters is resolved where the function is called (in opposition to where the function is defined). That gives the necessary space to solve OPs problem by yet another level of indirection: Instead of accessing myApp->someValue, a helper function is introduced, which can be declared before the definition of Property but implemented after Application is fully defined. (This could be a static member function of Property as well.) An example to demonstrate: #include <iostream> int getAppDefault(); struct Application; extern Application *pApp; struct Property { int value; Property(int value = getAppDefault()): value(value) { } }; struct Application { int valueDefault = 123; }; Application app; Application *pApp = &app; int getAppDefault() { return pApp->valueDefault; } int main() { Property prop1; std::cout << "prop1: " << prop1.value << '\n'; app.valueDefault = 234; Property prop2; std::cout << "prop2: " << prop2.value << '\n'; } Output: prop1: 123 prop2: 234 Demo on coliru To emphasize that value = getAppDefault() is in fact resolved when the constructor Property::Property() is called, I modified the Application::valueDefault before default-constructing prop2. And, of course, this works as well if the Property stores a pointer instead of the value itself: Demo on coliru
69,478,965
69,509,782
Compile C++ class with a header file to use it in python?
I have a my_class.h: // my_class.h namespace N { class my_class { public: void hello_world(); }; } with a my_class.cpp file. // my_class.cpp extern "C" { #include "my_class.h" } #include <iostream> using namespace N; using namespace std; void my_class::hello_world() { cout << "Hello, World!" << endl; } I want to create a shared object my_class.so file to use it in python. Therefore, I am using the g++ compiler. g++ -fPIC -shared -o my_class.so my_class.cpp Using the shared object in python my_class.so import ctypes my_class = ctypes.cdll.LoadLibrary('./my_class.so') my_class.hello_world I get the following error message: Exception has occurred: AttributeError ./my_class.so: undefined symbol: hello_world I do not know how to interpret this. Note: my_class.hello_world() results the same error
Much to talk about, but I'll try to be brief: extern "C" is going to make those symbols available in the C-syntax. (You do want this) C-syntax does not support classes or namespaces. the python dynamic library loader is grabbing ALL the symbols - not just your class. (It seems there is some confusion there with the naming scheme) To Fix: Simply eliminate your class and namespaces (or add a C-API pass-through). my_class.h extern "C" { void hello_world(); } my_class.cpp #include "my_class.h" #include <iostream> void hello_world() { std::cout<<"Hello, World" << std::endl; } After you build, use nm or objdump to verify that the symbol hello_world is defined and not mangled. Example: >> nm my_class.so | grep hello 0000000000000935 T hello_world And your python code will need an open close parenthesis to tell it to execute the function: import ctypes my_class = ctypes.cdll.LoadLibrary('./my_class.so') my_class.hello_world()
69,479,041
69,483,541
is there a z3 container that is equivalent to a map in C++?
I am working on a reverse engineering project where I am asked to perform backward slicing on assembly code. for a given assembly code register in a given assembly code function, I would like to detect all instructions inside the assembly function that perform an operation that updates that register. Long story short I represent the operations of these instructions as z3 expressions for example sub r2 r2 10 add r1 r2 3 register r1 is represented as (bvadd #x0000000d r2)). however for the case of an ldr instruction like so ldr r2,[r2, #13] add r1 r2 3 I want to represent memory as a map that has z3 expressions as keys and values so the ldr instruction should be a z3 expression of the form (z3_ctx.select(mem, i)) only now I want a map not an array in z3 so my question is how can I construct a map in z3 whose keys and values are z3 expressions as I want to represent the load operations from this map as z3 expressions similar to (z3_ctx.select(mem, i)) in case of a z3 array only now the i itself is a z3 expression (bvadd #x0000000d r2)
An SMTLib array from bit-vectors to bit-vectors would work for this just fine. From an API perspective, there's no difference between a map and an array in SMT-solving: You address it using bit-vectors, just like what you wanted to do. Your message suggests that you're worried you will not be able to "address" the array using a z3 expression? This isn't true. An array from bit-vectors to bit-vectors can be addressed with arbitrary z3 expressions of the right bit-vector type. If you tried the above an ran into issues, post the code that gave you errors. Otherwise, it should work just fine. (Having said that, this doesn't mean it'll be "performant." Memories are typically soft-spots for solvers from a performance perspective; but that's a whole another topic.)
69,479,278
69,479,353
Working of parameterized constructor in C++ when variables are initailized vs uninitialized
Below C++ code works. #include<iostream> using namespace std; class Complex{ private: int real, imag; public: Complex(int r=0, int i=0){ real = r; imag = i; } }; int main() { Complex c1(10, 5), c2(2, 4); Complex c3; } When the parameterized constructor's variables r and i are uninitialized(eg: Complex(int r, int i)), the compiler throws up the error main.cpp:19:13: error: no matching function for call to ‘Complex::Complex()’ 19 | Complex c3; | ^~ main.cpp:10:5: note: candidate: ‘Complex::Complex(int, int)’ 10 | Complex(int r, int i){ | ^~~~~~~. I understood this to be an issue with the statement Complex c3;. Pardon me for being naive, but it's unclear why it works this way in the initial code snippet itself. Hope someone can clarify this.
The Complex constructor you show, with default arguments, can be called with two, one or zero arguments. If no arguments is used then the default values will be used. But if you remove the default values, you no longer have a default constructor, a constructor that can be used without arguments. It's really exactly the same as normal functions with default argument values... Lets say you have this function: void foo(int arg = 0) { // Implementation is irrelevant } Now this can be called as: foo(123); // Pass an explicit argument Or as: foo(); // Equivalent to foo(0) If you remove the default value: void foo(int arg) { // Implementation is irrelevant } Then calling the function without any argument is wrong: foo(); // Error: Argument expected
69,479,670
69,480,706
Android How to enable position independent flag -fpic for c++ code
I am using a c++ class in my application to store my constants/urls etc. For that I have configured ndk and CMakeLists.txt file. So I only have two files in my jni folder which is app-config-native-lib.cpp and CMakeLists.txt. Following is my CMakeLists.txt file # For more information about using CMake with Android Studio, read the # documentation: https://d.android.com/studio/projects/add-native-code.html # Sets the minimum version of CMake required to build the native library. cmake_minimum_required(VERSION 3.4.1) # Creates and names a library, sets it as either STATIC # or SHARED, and provides the relative paths to its source code. # You can define multiple libraries, and CMake builds them for you. # Gradle automatically packages shared libraries with your APK. add_library( # Sets the name of the library. app-config-lib # Sets the library as a shared library. SHARED # Provides a relative path to your source file(s). app-config-native-lib.cpp) # Searches for a specified prebuilt library and stores the path as a # variable. Because CMake includes system libraries in the search path by # default, you only need to specify the name of the public NDK library # you want to add. CMake verifies that the library exists before # completing its build. find_library( # Sets the name of the path variable. log-lib # Specifies the name of the NDK library that # you want CMake to locate. log) # Specifies libraries CMake should link to your target library. You # can link multiple libraries, such as libraries you define in this # build script, prebuilt third-party libraries, or system libraries. target_link_libraries( # Specifies the target library. app-config-lib # Links the target library to the log library # included in the NDK. ${log-lib}) I want to enable Position independent flag-fpic to adhere the security constraints as it is explained here here. It is explained in this thread that we can pass flag in build gradle file in externalNativeBuild/cmake but I am not sure about it. My question is how we can enabe PIC executables for native code in Android? What flag should be used? And where to put that flag in build gradle file or CMakeLists file?
The option -fPIC is the default on Android. You can add other compiler options in CMakeLists.txt via: set_source_files_properties(myfile.c PROPERTIES COMPILE_FLAGS " -mfpu=neon -fno-vectorize")
69,479,974
69,480,330
Why a pointer to a class take less memory SRAM than a "classic" variable
i have a Arduino Micro with 3 time of flight LIDAR micro sensors welded to it. In my code i was creating 3 Global variable like this: Adafruit_VL53L0X lox0 = Adafruit_VL53L0X(); Adafruit_VL53L0X lox1 = Adafruit_VL53L0X(); Adafruit_VL53L0X lox2 = Adafruit_VL53L0X(); And it took like ~80% of the memory Now i am creating my objects like this Adafruit_VL53L0X *lox_array[3] = {new Adafruit_VL53L0X(), new Adafruit_VL53L0X(), new Adafruit_VL53L0X()}; And it take 30% of my entire program I Try to look on arduino documentation but i don't find anything that can help me. I can understand that creating a "classic" object can fill the memory. But where is the memory zone located when the pointer is create ?
You use the same amount of memory either way. (Actually, the second way uses a tiny bit more, because the pointers need to be stored as well.) It's just that with the first way, the memory is already allocated statically from the start and part of the data size of your program, so your compiler can tell you about it, while with the second way, the memory is allocated at runtime dynamically (on the heap), so your compiler doesn't know about it up front. I dare say that the second method is more dangerous, because consider the following scenario: Let's assume your other code and data already uses 90% of the memory at compile-time. If you use your first method, you will fail to upload the program because it would now use something like 150%, so you already know it won't work. But if you use your second method, your program will compile and upload just fine, but then crash when trying to allocate the extra memory at runtime. (By the way, the compiler message is a bit incomplete. It should rather say "leaving 1750 bytes for local variables and dynamically allocated objects" or something along those lines). You can check it yourself using this function which allows you to estimate the amount of free memory at runtime (by comparing the top of the heap with the bottom [physically, not logically] of the stack, the latter being achieved by looking at the address of a local variable which would have been allocated at the stack at that point): int freeRam () { extern int __heap_start, *__brkval; int v; return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval); } See also: https://playground.arduino.cc/Code/AvailableMemory/
69,480,128
69,493,071
clang-tidy bugprone-unused-return-value: how to check all functions?
I have clang-tidy checking for unused return values with bugprone-unused-return-value check. Unfortunately it only checks return values from list of functions specified with CheckedFunctions parameter. I would like to check usage of return value from all functions, but am not able to figure out what to write to CheckedFunctions to do this. What should I write to bugprone-unused-return-value's parameter CheckedFunctions for it to check all functions?
Unfortunately bugprone-unused-return-value check is not built to check all functions. You can either specify CheckedFunctions or if you omit the specification then a default list of functions will be used. There is no possibility of using wildcards or regular expressions here. See the documentation. I also checked the source code of the check just to be sure but in current version of clang-tidy (14) this can't be done.
69,480,604
69,482,653
C++ SDL2 can't load any file
I'm using SLD2 in order to make a game, All was working perfectly since now. I think there is a problem the loading file system. for example, when i tried to load a bmp : #include <iostream> # include "SDL.h" int main(int argc, char* argv[]) { SDL_Init(SDL_INIT_VIDEO); // Initialize SDL2 SDL_Window* window = SDL_CreateWindow("game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1000, 500, SDL_WINDOW_OPENGL); SDL_Renderer* render = SDL_CreateRenderer(window, -1, 0); SDL_Surface* image = SDL_LoadBMP("../background.bmp"); printf(SDL_GetError()); return 0; } the SLD_GetError() function return : couldn't load ( some random weird chars) and it's the same for SDL mixer it seems that no file (or any type of file) can be load by any SDL2 features... Why ? (the exe is in a subfolder, so the background path is correct) here is a screenshot
There is nothing wrong with SDL2. The path you are entering is probably invalid because it says "couldn't load ( some random weird chars )", that means SDL couldn't find the file. You are using ../ to indicate that your background.bmp file is in the parent directory of the current working directory. If you are using an IDE and then build it, SDL expects the file to be in the parent directory of your project folder. If you then run the executable, it expects the file to be in the parent directory of your executable. So try using an absolute path, for example, C:\users\path-to-file\background.bmp. If you use that path system, SDL always search for the background.bmp in the given path no matter where your executable is located or where you built the program. Also be aware of escape sequences. use \\ for backslash. Or you can just use /.
69,480,630
69,483,669
Boost concept check warnings
Given this code using boost 1.75 / gcc 11 #include <boost/bimap.hpp> #include <string> #include <iostream> int main() { typedef boost::bimap<std::string, int> bimap; bimap animals; animals.insert({"cat", 4}); animals.insert({"shark", 0}); animals.insert({"spider", 8}); std::cout << animals.left.count("cat") << '\n'; std::cout << animals.right.count(8) << '\n'; } I get many warnings such as boost concept failed ... More logs: https://godbolt.org/z/6Ge5vxYrc How to fix this if I do not have the ability to upgrade boost
As the messages suggest, you can suppress the -Wnonnull diagnostics: g++ -std=c++17 -Wno-nonnull ... https://godbolt.org/z/YEafWTqex
69,480,783
69,485,658
Qt 6.2: QMediaPlayer & QByteArray
Good day. Has anyone tried QMediaPlayer in Qt 6.2 already? I'm trying this code, but Media Status always remains as "NoMedia" and no any sound :). Full test project: https://github.com/avttrue/MediaPlayerTest #include "mainwindow.h" #include <QDebug> #include <QBuffer> #include <QFile> #include <QAudioOutput> #include <QMediaPlayer> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { QFile file("../test/Bankrobber.mp3"); if(!file.open(QIODevice::ReadOnly)) qDebug() << "File not opened"; qDebug() << "File size:" << file.size(); // File size: 11181085 QByteArray ba = file.readAll(); qDebug() << "ByteArray size:" << ba.size(); // ByteArray size: 11181085 QBuffer* buffer = new QBuffer(this); buffer->setData(ba); if(!buffer->open(QIODevice::ReadOnly)) qDebug() << "Buffer not opened"; qDebug() << "Buffer size:" << buffer->size(); // Buffer size: 11181085 buffer->seek(qint64(0)); auto audioOutput = new QAudioOutput(this); auto player = new QMediaPlayer(this); player->setAudioOutput(audioOutput); audioOutput->setVolume(50); player->setSourceDevice(buffer); qDebug() << "Device:" << player->sourceDevice(); // Device: QBuffer(0x563180493020) QObject::connect(player, &QMediaPlayer::mediaStatusChanged, [=](QMediaPlayer::MediaStatus status) { qDebug() << "MediaStatus:" << player->mediaStatus() << "|" << status; }); QObject::connect(player, &QMediaPlayer::errorOccurred, [=](QMediaPlayer::Error error) { qDebug() << "Error:" << player->errorString() << "|" << error; }); QObject::connect(player, &QMediaPlayer::playbackStateChanged, [=](QMediaPlayer::PlaybackState state) { qDebug() << "PlaybackState:" << player->playbackState() << "|" << state; }); player->play(); qDebug() << "MediaStatus:" << player->mediaStatus(); // MediaStatus: QMediaPlayer::NoMedia }
As the docs points out: void QMediaPlayer::setSourceDevice(QIODevice *device, const QUrl &sourceUrl = QUrl()) Sets the current source device. The media data will be read from device. The sourceUrl can be provided to resolve additional information about the media, mime type etc. The device must be open and readable. For macOS the device should also be seek-able. Note: This function returns immediately after recording the specified source of the media. It does not wait for the media to finish loading and does not check for errors. Listen for the mediaStatusChanged() and error() signals to be notified when the media is loaded, and if an error occurs during loading. (emphasis mine) QMediaPlayer does not know how to deduce the file format so it does not load it. The solution is to point out that it is an mp3: player->setSourceDevice(buffer, QUrl("foo.mp3"));
69,481,286
69,481,509
how to store count of values that are repeated in an array into map in c++?
I was trying to store count of words repeated in an array of string... int countWords(string list[], int n) { map <string, int> mp; for(auto val = list.begin(); val!=list.end(); val++){ mp[*val]++; } int res = 0; for(auto val= mp.begin(); val!=mp.end(); val++){ if(val->second == 2) res++; } return res; } but I was getting error like: prog.cpp: In member function int Solution::countWords(std::__cxx11::string*, int): prog.cpp:14:32: error: request for member begin in list, which is of pointer type std::__cxx11::string* {aka std::__cxx11::basic_string<char>*} (maybe you meant to use -> ?) for(auto val = list.begin(); val!=list.end(); val++){ ^ prog.cpp:14:51: error: request for member end in list, which is of pointer type std::__cxx11::stri................. someone please look into this once.
The reason for the error is that list is an array, which does not have a begin method (or any other method). This could be fixed by changing the function to take a std::vector instead of an array. If you want to keep it as an array, the for loop should be changed to this, assuming n is the length of the array: for(auto val = list; val != list + n; val++) In C and C++, an array is somewhat equivalent to a pointer to the first element of the array; thus list gives the start pointer, and list + n gives a pointer to after the end of the array.
69,481,294
69,481,362
Use initializer list as default value for function/method parameter
I want to do something like void A (int a[2] = {0,0}) {} but I get <source>(1): error C2440: 'default argument': cannot convert from 'initializer list' to 'int []' <source>(1): note: The initializer contains too many elements (MSVC v19 x64 latest, doesn't work with gcc x86-64 11.2 either) Again, I cannot figure what the c++ powers to be fancied as the proper syntax here.
The reason this does not work is that this void A (int a[2]) {} is just short hand notation for void A (int* a) {} You cannot pass arrays by value to functions. They do decay to pointers to the first element. If you use a std::array<int,2> you can easily provide a default argument: void foo(std::array<int,2> x = {2,2}) {}
69,481,611
69,482,410
Using function to create a grading system
Question: I honestly have no idea how to answer test #1, it only needs one input and will output one when the question is asking the user will input ten (10) consecutive numeric grades that may or may not have a decimal. #include <iostream> #include <array> #include <iomanip> char getLetterGrade(double); using namespace std; int main(){ const int students_number = 10; array<double, students_number> grades; array<char, students_number> letters; for(double & grade : grades) cin >> grade; for(size_t i = 0; i < students_number; ++i) letters[i] = getLetterGrade(grades[i]); for(size_t i = 0; i < students_number; ++i) cout << fixed << setprecision(2) << grades[i] << "=" << letters[i] << endl; return 0; } char getLetterGrade(double grade){ if(grade >= 95 && grade <=100) return 'A'; if(grade > 89 && grade< 95) return 'B'; if(grade > 84 && grade< 90) return 'C'; if(grade > 79 && grade< 85) return 'D'; if(grade > 75 && grade< 80) return 'E'; if(grade > 40 && grade< 76) return 'F'; return 'X'; } Test #1 --- Input --- -100 --- Program output --- -100.00=X 0.00=X 0.00=X 0.00=X 0.00=X 0.00=X 0.00=X 0.00=X 0.00=X 0.00=X --- Expected output (text)--- -100.00=X
"Using function to create a program that validate and evaluate 10 numeric grades to its respective letter grade" Well as given, the assignment does not require you to compute the average of the grades. On the other hand, from the code sample given by your teacher, you are expected to define your grade to letter conversion inside a function (here getLetterGrade()) and not directly into the main() function of your program. For the program itself, as suggested in comments, you better have to use containers (for example std::array) to store the grades and letters. It would prevent you from having to create 20 variables which is not really convenient and hurts a lot the readability (and maintainability) of your code. For the method, you may divide your process into 4 steps: Create the containers. Read the grades from user input and store them into the container dedicated to the grades. Iterate over the previous container, call the getLetterGrade() function for each grade and store the result into the container dedicated to the letters. [Optional] Display the letters to validate the program (another iteration) Possible solution: #include <iostream> #include <array> char getLetterGrade(double); int main() { const int students_number = 10; // Create the arrays (more convenient than creating 20 variables) std::array<double, students_number> grades; std::array<char, students_number> letters; // Read the grades and store them into `grades` for(double & grade : grades) std::cin >> grade; // Deduce the letter for the given grades and store them into `letters` for(std::size_t i = 0; i < students_number; ++i) letters[i] = getLetterGrade(grades[i]); // Display the "- [grade]: [letter]" for(std::size_t i = 0; i < students_number; ++i) std::cout << "- " << grades[i] << ": " << letters[i] << '\n'; return 0; } char getLetterGrade(double grade) { if(grade > 94) return 'A'; if(grade > 89) return 'B'; if(grade > 84) return 'C'; if(grade > 79) return 'D'; if(grade > 74) return 'E'; if(grade > 40) return 'F'; return 'G'; } Note: From this proposal, you just have to change the value of students_number in order to make it work with a different number of students. Demo
69,481,713
69,507,167
how to link a c++ library to a c++ source code when it has a specific linker script to compile?
i have these files:- /lib kernel.hpp kernel.cpp main.cpp when i use gcc -m32 -c main.cpp -lstdc++ -o main.o -llib/kernel.hpp it says [function name]([type of argument 1], [type of argument 2]) is not declared in this scope how to fix?
I started writing a comment, but got to be too long, so we'll make it an answer instead. I don't think it in fact will answer your question, but it may point you in the right direction. Let's clear up a misconception, c++ is not a superset of c; there are c constructs that c++ does not support. If your code is c++, you need to compile it with a c++ compiler. The problems you've been describing all indicate that compilation is failing; you're not at the point where the linker is involved. The compile command you provided in your question had a -c flag, which tells the compiler to stop after the compilation step - so there's no point in having a -lstd++ flag in addition. For the compiler to find kernel.hpp you need a -I flag which indicates the directory where kernel.hpp can be found. That's what I was suggesting in my first comment. To sum up, as shown in the original question, you're using the wrong compiler and the wrong flags for what you want to do.
69,482,003
69,482,191
How to convert int to string in a ternary operation
When trying to do a ternary operation using an integer and string such as: for (int num = 0; num < 100; num++) { cout << (i % 10 == 0) ? "Divisible by 10" : num; } You end up with the following exception E0042: operand types are incompatible ("const char*" and "int") If you were to try to cast num to const char* by doing (const char*)num you will end up with an access violation. If you do (const char*)num& instead, you get the ASCII character corresponding to the value. For numbers greater than 10 how can you quickly cast that integer into a string? (Preferably in the same line)
If you insist on the conditional operator, you could write this: for (int num = 0; num < 100; num++) { (num%10==0) ? std::cout << "Divisible by 10" : std::cout << num; } If you want to stay with yours, you need to convert the values to some compatible types. There is no way around that. The conditional operator is not an equivalent replacement for an if-else statement and often the latter is much clearer: for (int num = 0; num < 100; num++) { if (num%10==0) { std::cout << "Divisible by 10"; } else { std::cout << num; } } For numbers greater than 10 how can you quickly cast that integer into a string? (Preferably in the same line) std::to_string can convert numbers to strings. PS: To illustrate an example where an if-else cannot be used and the conditional operator is actually useful, consider the initialization of a reference. You cannot write: int x = 0; int y = 0; int& ref; // nope, error if (condition) ref = x; else ref = y; but you can write: int& ref = (condition) ? x : y; There are other cases where the conditional operator is useful. It's purpose is not just to save a line of code compared to an if-else.
69,482,527
69,483,791
Changing array value through a function
I want to design a program of n = 3 instances. Each instance is pointing to an 'instance' position of an array. Each instance is composed of two values: {error, control}. When calling a function "run_instance" these two values change to other ones. #include <iostream> #include <stdio.h> #include <stdlib.h> #include <time.h> using namespace std; int main() { int Ki = 6; int Kp = 4; int n = 3; int arr[n][2] = { {0.1, 11}, {0.001, 21}, {0.0001, 31} }; double measured_error = 0.3; int instance = 2; run_instance(instance, measured_error, Kp, Ki); } double run_instance(int instance, double measured_error, int Kp, int Ki) { //new value = 21 + Kp * measured_error + (Ki-Kp)*0.001 (last error of this instance) //update arr[n][2] as{ // {0.1, 11}, // {measured_error, new_value}, // {0.0001, 31} // } //return new value = 21 + Kp * measured_error + (Ki-Kp)*0.001 (last error of this instance) }
There are a few problems: n should be const or constexpr: const int n = 3; or constexpr int n = 3; arr should be an array of doubles: double arr[n][2] { ... }; An array should be added in the parameter list in run_instance: double run_instance(double** arr, int instance, double measured_error, int Kp, int Ki) And finally (whew!) run_instance should be forward declared above main: double run_instance(double**, int, double, int, int);
69,482,846
70,251,547
Template argument deduction Doesn't Work for Function Template <unresolved overloaded function type>
I am trying to understand how template argument deduction works in C++. And so writing out different examples. One such example which doesn't work and i can't understand why is given below: #include<iostream> template<int var, typename T> void func (T x) { std::cout<<x<<std::endl; } template<typename T> void SomeFunc(T a) { a(6); } int main() { func<5, int>(10);//this work as expected func<5>(20);//this works as well using template argument deduction SomeFunc(func<5,int>) ;//this works as well //the next two calls doesn't work SomeFunc(func<5>);//this doesn't work. Why doesn't template argument deduction works here SomeFunc(func<5>(20));//this doesn't work either. return 0; } In the above example, the statement SomeFunc(func<5>); doesn't work. My thinking is that when the compiler tries to instantiates SomeFunc<> it needs its template type parameter. But we have passed func<5> as the function call argument without actually calling(specifying the call argument to func itself) func so there is no way to deduce the second parameter and so it doesn't work. My first question is that is my analysis of why this call fails correct? If not then why doesn't it work. Next in the statement SomeFunc(func<5>(20)); i have specified the function call argument 20 to func which was not specified in the previous call. But still this statement doesn't work. Why is this so? While reading about template argument deduction i also came across the following statement: Deduction only works for immediate calls. But i could not understand what the above quoted statement means. It may have to do something with the fact that complete type or incomplete type used as template argument but i am not sure.
SomeFunc(func<5,int>); You pass a pointer to the function func<5,int> and T becomes void(*)(int) which is fine. It also works inside SomeFunc when you use the function pointer a to call the function it is pointing at. SomeFunc(func<5>); Deduction is not possible. The compiler is not able to look forward to see that inside SomeFunc you will call a(6) so therefore it must instantiate func<5,int> and make a point at it. SomeFunc(func<5>(20)); Here you actually call func<5,int> (with the argument 20) and pass the return value from that call into SomeFunc. There is no return value from func<5,int> since it's void and void a; is not valid. If it had been valid, the next problem would have been that you try to call a in SomeFunc. The argument to SomeFunc must be a callable of some sort or else a(6); will fail.
69,482,892
69,483,004
Please explain the use of for_each function in this c++ code
I was going through techiedelight article link I didn't get the meaning of [&m](char &c) { m[c]++; } in std::for_each(s.begin(), s.end(), [&m](char &c) { m[c]++; }); #include <iostream> #include <unordered_map> #include <algorithm> int main() { std::unordered_map<char, int> m; std::string s("abcba"); std::for_each(s.begin(), s.end(), [&m](char &c) { m[c]++; }); char ch = 's'; if (m.find(ch) != m.end()) { std::cout << "Key found"; } else { std::cout << "Key not found"; } return 0; } Someone please explain how it is working. Thanks in advance.
[&m](char &c) { m[c]++; } this is a lambda. A lambda is an anonymously typed function object using shorthand. It is shorthand for roughly: struct anonymous_unique_secret_type_name { std::unordered_map<char, int>& m; void operator()(char& c)const { m[c]++; } }; std::for_each(s.begin(), s.end(), anonymous_unique_secret_type_name{m} ); the [&m](char &c) { m[c]++; } both creates the type and constructs an instance. It captures (by reference) the variable m, which it exposes as m within its body. As a function-like object (aka a function object), it has an operator() that can be called like a function. Here this operator() takes a char& and returns void. So for_each calls this function object on each element of the ranged passed (in this case, the string).
69,483,490
69,485,329
Apply stateful lambda to integer sequence values
I am playing around with trying to implement the numeric literal operator template. #include <string_view> #include <cstdint> #include <cmath> #include <iostream> #include <boost/mp11/integer_sequence.hpp> #include <boost/mp11/algorithm.hpp> using namespace boost::mp11; template <char... Cs> [[nodiscard]] constexpr auto operator""_c(){ int weight =std::pow(10, sizeof... (Cs)); // unused, would like to transform it using lambda that mutably captures // weight using ints = index_sequence<sizeof... (Cs)>; // ugly fold way auto val = ((weight/=10,(int)(Cs-'0')*weight) + ...); return val; } int main(){ std::cout << 0_c << std::endl; std::cout << 00_c << std::endl; std::cout << 01_c << std::endl; std::cout << 123_c << std::endl; } This code works for simple cases(correctness is not important, e.g. negative numbers), it is just an example, but code looks ugly and clang emits a warning for modifying weight multiple times, so I guess code is buggy(undefined or unspecified behavior) although it seems to work... Now I wonder is there a way for me to transform the ints I use(it is from boost::mp11, but same thing exists in std::) with a stateful lambda (that modifies weight). So I would like to transfer ints, that are <0,1,2> into something like <100,10,1> I presume this has been asked before but this is very hard to search for. To be clear: operator "" is just a toy problem, my real question is about mapping the values of integer sequence with a stateful lambda. Also if not clear from question: I am perfectly happy to use boost mp11, but could not find anything in the docs.
So I would like to transfer ints, that are <0,1,2> into something like <100,10,1> First, you can convert std::index_sequence to std::array, then perform your operations on it as you normally do, and finally, convert std::array to std::index_sequence again. In order for the stateful lambda to work at compile-time, we can accept a function that can return the stateful lambda then get it internally: template<std::size_t... Is> constexpr auto transform_seq(std::index_sequence<Is...>, auto get_op) { // index_sequence -> array constexpr auto arr = [op = get_op()]() mutable { std::array<std::size_t, sizeof...(Is)> arr{Is...}; for (auto& value : arr) value = op(value); return arr; }(); // array -> index_sequence constexpr auto seq = [&]<std::size_t... Js>(std::index_sequence<Js...>) { return std::index_sequence<std::get<Js>(arr)...>{}; }(std::make_index_sequence<arr.size()>{}); return seq; }; Then you can perform the index_sequence conversion according to op you pass in: using input1 = std::index_sequence<0,1,2>; auto gen_op1 = [] { return [w = 1000](auto x) mutable { w /= 10; return w; }; }; using res1 = decltype(transform_seq(input1{}, gen_op1)); static_assert(std::same_as<res1, std::index_sequence<100, 10, 1>>); using input2 = std::index_sequence<0,1,2,3>; auto gen_op2 = [] { return [b = true] (auto x) mutable { b = !b; return b * 10 + x; }; }; using res2 = decltype(transform_seq(input2{}, gen_op2)); static_assert(std::same_as<res2, std::index_sequence<0,11,2,13>>); Demo.
69,483,521
69,484,057
template deduction and implicit constructors
Is there a way to make template deduction work with (implicit) conversion? Like the following example: template<typename T> struct A {}; template<typename T> struct B { B(A<T>); // implicit A->B conversion }; template<typename... Ts> void fun(B<Ts>...); int main() { A<int> a; fun(B(a)); // works fun(a); // does not work (deduction failure) } My thoughts: If A is a subclass of B, everything works. That means that deduction can do implicit conversion using upcasting. So it seems weird that it can not do implicit conversion using a constructor. Overloading fun for A and B is possible in principle, but for multiple parameters, there are just too many combinations Adding a deduction guideline (template<typename T> B(A<T>)->B<T>;) does not change anything. EDIT: some context: In my actual code, A is a (large) container, and B is a lightweight non-owning view object. The situation is similar to the fact that std::vector<T> can not be implicity converted to std::span<T> during deduction of T, even though for any concrete T, such a conversion exists.
Template argument deduction does not consider any potential type conversions - mainly because deduction happens before any such conversions can happen. Basically, when the compiler sees fun(a), it first gathers a set of foo functions that are eligible to service that call. If a foo function template is found, the compiler tries to generate a concrete function from it by substituting the template arguments with the types of arguments passed in the call statement. That's where the template argument deduction happens. No type conversion can happen here because there is no concrete type to convert to. In your example, B<T> is not a type to convert to because T is unknown and it cannot be discovered from an argument of type A<int>. It is also not known whether an arbitrary instance of B<T> will be constructible from A<int> because different specializations of B may have different sets of constructors. Hence the deduction fails in your case. If the deduction succeeds, the concrete function (with the deduced argument types) is added to the candidate set. When the set of candidates is gathered, then the best matching candidate is chosen. At this point argument conversions are considered. The conversions are possible since the candidates are no longer templates, and the target types for conversions are known. What you could do to work around it is to allow the compiler to deduce the template as well and then construct B<T> explicitly: template<typename... Ts> void fun_impl(B<Ts>...); template<template<typename> class X, typename... Ts> std::enable_if_t<(std::is_constructible_v<B<Ts>, X<Ts>> && ...)> fun(X<Ts>... args) { fun_impl(B<Ts>(args)...); } int main() { A<int> a; fun(B(a)); // works, instantiates fun<B, int> fun(a); // works, instantiates fun<A, int> }