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
73,147,274
73,161,012
How to build Opencv code in a docker file
I want to build and run a c++ opencv code using docker. Here is my dockerfile: FROM nvidia/cuda:11.5.0-cudnn8-runtime-ubuntu20.04 FROM ubuntu ARG DEBIAN_FRONTEND=noninteractive RUN apt-get update && \ apt-get install -y \ g++ git wget cmake sudo RUN apt-get install -y \ build-essential cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev \ python3-dev python3-numpy libtbb2 libtbb-dev libjpeg-dev libpng-dev libtiff-dev libdc1394-22-dev \ libcanberra-gtk-module libcanberra-gtk3-module RUN git clone https://github.com/opencv/opencv.git && \ cd /opencv && mkdir build && cd build && \ cmake -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local .. && \ make -j"$(nproc)" && \ make install && ldconfig The above commands makes my opencv libs, but I don't how to use it to run the actual code. I added this two lines at the end of the dockerfile (wav.cpp is the name of my cpp file that I want to run): COPY . . RUN g++ -o wav wav.cpp But at the end I get this error, which obviously says it can't find the opencv headers. wav.cpp:2:10: fatal error: opencv2/imgproc.hpp: No such file or directory 2 | #include "opencv2/imgproc.hpp" | ^~~~~~~~~~~~~~~~~~~~~ compilation terminated. Now how should I resolve this header (and lib) dependency problem? Thank you.
Using @emrhzc's answer I could build my code inside the dockerfile. Now my final working command is: RUN g++ -o wav wav.cpp `pkg-config --cflags --libs opencv4`
73,147,898
73,149,890
Inherit CTAD constructor
I have derived from std::tuple and but was unable construct the derived class from an initializer list due to issues with class template argument deduction. Is there a better way to construct such a class beyond just giving it an already constructed tuple first{ std::tuple{1, 1.0f, 1u} };. template <typename T, typename... Types> struct first : public std::tuple<T, Types...> { //using std::tuple<T, Types...>::tuple; template<typename F> requires std::invocable<F, T> auto transform(F f) { auto result = *this; std::get<0>(result) = f(std::get<0>(result)); return result; } }; int main() { //auto tuple = first{ 1, 1.0f, 1u }; auto tuple = first{ std::tuple{1, 1.0f, 1u} }; auto tuple2 = tuple.transform([](auto a) {return a + 3; }); }
Inherited constructors are not part of CTAD. You might replicate std::tuple's CTAD: template <typename T, typename... Types> first(T, Types...) -> first<T, Types...>; // auto tuple = first{1, 1.0f, 1u}; // is ok now // auto tuple = first{ std::tuple{1, 1.0f, 1u} }; // broken now Demo
73,147,987
73,148,066
Understand shell script interpreter with custom shell
I try to understood how shell script interpreter working. for example i wrote custom shell with c++ : #include <iostream> #include <string> using namespace std ; int main() { string input; while (1) { cout << "prompt:> "; cin >> input; if(input=="exit") return 0; else if(input=="test") cout << "You executed test command\n"; else cout << "Unknown command.\n"; } } now i wrote a script like this : #!/PATH/TO/COMPILED/SHELL test wrong_command1 wrong_command2 exit Actually this script not working and i want to understand what part of my thinking is wrong . Note: I executed this script on /bin/bash shell . can i say ,my c++ code is: interactive shell How interpreters work on shell scripts ? #!/PATH/TO/COMPILED/SHELL How can fix code or script to activate interpreting feature ?
No idea what that means If you compile your program to /tmp/a.out and have an executable file script with: #!/tmp/a.out test wrong_command1 wrong_command2 exit which you invoke on command line as ./script then the shell running the command line will invoke /tmp/a.out ./script. I.e. looks at the shebang, invokes that command and passes the script as its first argument. The rest is up to that command. There is no interpreting feature in C++, you have to write it yourself, what you have is a good start except you need to read from the passed file argument, not stdin. Also std::getline might come handy.
73,148,061
73,148,647
Find Key index in a rotated sorted array using binary sort?
here in this code i am facing issues regarding my output of find the correct index for the key. the output of pivot element is correct but i was unable for find the error in the key index part of my code . can some debug it for me please or at least tell me where i was doing it wrong. this is a code of me trying to find the index of key element in a sorted rotated array and my approach is as follows first i have to find the pivot element than i compare the size of element at pivot index and size of key element if the size is greater than pivot and less the size of array than i binary search between pivot and ( n -1 ) : which the last index of array . and if the size is small than i search between 0th index and pivot index. so correct me where i am wrong. #include<bits/stdc++.h> using namespace std; int getPivot ( int arr[] , int size){ int start =0; int end = size-1; int mid = start + ( end - start)/2; while( start < end ){ if( arr[mid] > arr[0]){ start = mid +1; } else{ end = mid; } mid = start + ( end - start )/2; } return end; } int binarySearch ( int arr[] , int size , int s , int e , int key){ int start = s; int end = e; int mid = s+( e-s )/2; while ( start <= end ){ if( arr[mid] == key){ return mid; } else if ( arr[mid] > key ){ end = mid -1; } else{ start = mid +1; } mid = start+( end - start )/2; } return start ; } int main(){ int n,k; cin>>n>>k; int arr[n]; for( int i=0; i<n; i++){ cin>>arr[i]; } int pivot = getPivot( arr , n); cout<<" the index of Pivot element is : "<<pivot<<endl; if( k >= arr[pivot] && k<= arr[n-1] ){ cout<<" the index of the key is : " <<binarySearch( arr , n , pivot , ( n-1) , k)<<endl; } else{ cout<<" the index of the key is : " <<binarySearch( arr , n , 0 , (pivot-1) , k)<<endl; } return 0; }
This looked supsicous: int mid = s+( e-s )/2; It's not using modulo arithmetic correctly. There's confusion of comparing arr[mid] with normalized vs. unnormalized coordinates and how that applies to recomputing start and end on each iteration of the binary search loop. You want start and end to be recomputed in the "normalized" space, but mid needs to be adjusted for the pivot index value. This also looked suspicious int main: if( k >= arr[pivot] && k<= arr[n-1] ){ cout<<" the index of the key is : " <<binarySearch( arr , n , pivot , ( n-1) , k)<<endl; } else{ cout<<" the index of the key is : " <<binarySearch( arr , n , 0 , (pivot-1) , k)<<endl; } If I understand the problem correctly, the algorithm takes in a sorted array that could be rotated. Where the input read from stdin could be something like the following: 10 4 // n = 10, key=4 9 10 11 12 13 1 2 3 4 5 // the sorted rotated array So in the above example if key==4, then we want to return 8 as the index since array[8] == 4 Here's a cleaned up version of your code. The main changes are this: Use the correct header includes Removed the variable length array and replaced with std::vector. Fixed the bug in binarySearch. Also, the e parameter isn't actually needed with this fix, so I removed that. binarySearch will return -1 if the element can't be found instead of start Fixed main to just call binarySearch with the size and pivot index in a consistent way. No need to have two versions of calling it. Nor do you need to explicitly pass the end index. getPivot had some bugs in it too. So I fixed that with similar modulo arithmetic. #include <iostream> #include <vector> using namespace std; int getPivot(int arr[], int size) { int start = 0; int end = size - 1; if (size <= 1) { return 0; } while (start <= end) { int len = end - start + 1; int prev = (start + size - 1) % size; int mid = (start + end) / 2; if (arr[start] < arr[prev]) { return start; } if (arr[start] <= arr[mid]) { start = mid+1; } else { end = mid; } } return -1; } int binarySearch(int arr[], int size, int pivot, int key) { int start = 0; // start and end are in the "normalized" index space int end = size - 1; while (start <= end) { int mid = (start + end) / 2; int actualMid = (pivot + mid) % size; // actualMid is the denomalized conversion of mid using modulo arithmetic if (arr[actualMid] == key) { return actualMid; } else if (arr[actualMid] > key) { end = mid - 1; // adjust end in normalized index space } else { start = mid + 1; // adjust start in normalized index space } } return -1; } int main() { int n, k; cin >> n >> k; std::vector<int> arr(n); for (int i = 0; i < n; i++) { cin >> arr[i]; } int pivot = getPivot(arr.data(), n); cout << " the index of Pivot element is : " << pivot << endl; cout << " the index of the key is : " << binarySearch(arr.data(), n, pivot, k) << endl; return 0; }
73,148,526
73,148,594
Boolean If Statement with a Pointer to a Class
#define NULL 0 class Sample{ public: Sample():m_nNumber(0){} Sample(int nNumber):m_nNumber(nNumber){} ~Sample(){} int GetNumber(){return m_nNumber;} void SetNumber(int nNumber){m_nNumber = nNumber;} private: int m_nNumber; }; Sample* TestSample(Sample* mSample){ int nNumber = mSample->GetNumber(); if ( nNumber%2 == 0) return mSample; return NULL; } void TestNumber ( int nSample ) { Sample mTest(nSample); Sample* mTest2 = TestSample(&mTest); if ( mTest2 ) /* Is this statement valid? or an Undefined Behaviour? */ { std::cout<<"Sample is Even"<<std::endl; } else { std::cout<<"Sample is Odd"<<std::endl; } } int main() { TestNumber( 10 ); TestNumber( 5 ); } Given the following snippet I have a few Questions. Is it an undefined behavior to return a 0 (NULL) from a function that returns a class pointer? When doing a Boolean if statement on a pointer to a User defined class (if it's even allowed or does not result in an undefined behavior), does it evaluate the address of the pointer, or (EDIT) the value of the pointer? I am using VS2008 due to the code I'm working on is a Legacy Source and it doesn't have updated third party Libraries.
Both is perfectly valid and though some might argue better ways exist to handle this, still used frequently. NULL is a valid value for a pointer. Checking if a pointer is NULL or not is valid (that is what an if statement is doing in C++, checking if the value given is not zero). What is not "allowed" is dereferencing a NULL pointer. So any usage of it beyond checking whether it is NULL would result in some ugly behaviors.
73,149,011
73,149,053
Throw when reassigning
try { object = mayThrow(); } catch (const std::exception& exc) { //... } If mayThrow() actually throws, will the original object be untouched? Or is it better to do it this way? try { Object newObject = mayThrow(); object = std::move(newObject); } catch (const std::exception& exc) { //... }
Unless mayThrow() has direct access to object and does some monkeying within, the final assignment happens if and only if mayThrow() returns successfully and the object stays unchanged otherwise.
73,149,117
73,149,210
Class Pointer reference inside of another Class defined below? (C++ 14, VS 2019)
Problem Summary I'm attempting to write a series of classes in C++ 14, that are all supposed to be inside of the same class, and have pointer fields that point to object instances of each one of the classes. They are all also supposed to have constructors that assign those fields, using arguments that are pointers to the other class instances. I'm running into a problem where I am unable to call the constructor with the pointer arguments. Below is an illustration of my problem: Defined in header file: class A; class B; class C; class A { public: class B { public: B(C* arg) { ptr = arg; } C* ptr; }; class C { public: ... }; }; Runner code in cpp file: A::C TEST_C = *new A::C(); A::B TEST_B = *new A::B(&TEST_C); The line which initializes TEST_B with the constructor pointer argument call gives the following two errors in the VS 2019 compiler: Error C2664 'A::B::B(C *)': cannot convert argument 1 from 'A::C *' to 'C *' Error C2512 'A::B': no appropriate default constructor available My Attempts The first error line got me thinking that I may need to change my forward class declarations to include their respective parent classes too, as such: class A; class A::B; class A::C; However, that appears to break the reference to class C completely, and any references to it in the header above it's definition treat it as an undefined reference (Identifier "C" is undefined.). It's as if there were no forward declarations at all. Adding A:: to each reference to class C in the rest of the header as such: class A { public: class B { public: B(A::C* arg) { ptr = arg; } A::C* ptr; }; class C { public: ... }; }; didn't help either, instead the compiler tells me Class "A" has no member "C".. However, one interesting thing that I did notice, was the fact that if I change the argument being passed to the constructor call for class B, to nullptr, that is: A::B TEST_B = *new A::B(nullptr); then the code gets compiled without problems. To me, that meant that this is most likely an issue with my forward class declarations, where the compiler sees that there are classes B and C declared, but it doesn't get to reading the actual content of the classes prior to attempting to reference them. Is what I'm trying to accomplish here even possible with C++? Is there a way I should be doing this properly, that I'm not seeing? Thank you in advance for reading my post, any help is appreciated!
The problem is that you've forward declared class C in global namespace instead of class scope A. This means that there are two different class named C one of which is declared to be in the global namespace ::C and the second one as an inner class A::C. To solve this, just move the forward declaration of class C to inside class scope A as shown below: header.h class A { public: class C;// forward declaration moved here inside class scope A class B { public: B(C* arg) { ptr = arg; } C* ptr; }; class C { public: }; }; Working demo Also, be careful about other logical bugs like memory leak(if any) in your program.
73,149,385
73,149,923
usr/bin/ld skipping incompatible ./libSPECcon.so when searching for -lSPECcon
Currently, I'm using Ubuntu 22.04. I have main.cpp and a .so file. I got this error when i try to compile with following command g++ -L. -Wall -o code main.cpp -lSPECcon. .so file and main.cpp are in the same folder It gives me this output: main.cpp: In function ‘int main(int, char**): main.cpp:51:22: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings] 51 | char *port = "ttyUSB0"; | ^~~~~~~~~ main.cpp:58:26: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings] 58 | char *filename = "/home/karun/spec/SPECcon/SPECcon_1.3/Examples/c++/example_cs.txt"; | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ main.cpp:98:21: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings] 98 | char *arg = "3"; | ^~~ main.cpp:99:21: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings] 99 | char *cmd = "M"; // Executing the command *para:gain from example.txt | ^~~ main.cpp:42:34: warning: unused variable ‘DLL_supported_baudrates’ [-Wunused-variable] 42 | SPEC_supported_baudrates DLL_supported_baudrates = (SPEC_supported_baudrates)dlsym(hGetProcIDDLL, "SPEC_supported_baudrates"); | ^~~~~~~~~~~~~~~~~~~~~~~ main.cpp:54:13: warning: variable ‘ret’ set but not used [-Wunused-but-set-variable] 54 | int ret = DLL_identify_spectrometer(port, baud, firmware); | ^~~ /usr/bin/ld: skipping incompatible ./libSPECcon.so when searching for -lSPECcon /usr/bin/ld: cannot find -lSPECcon: No such file or directory /usr/bin/ld: skipping incompatible ./libSPECcon.so when searching for -lSPECcon collect2: error: ld returned 1 exit status How do i solve this problem?
I solve the problem by linking my .so file to /usr/lib. This question helped me: usr/bin/ld: cannot find -l<nameOfTheLibrary>
73,149,905
73,150,241
Which STD container to use to get [] operator and erase elements without moving memory around?
I used std::vector<MyClass> and everything was fine until I had to use erase() function. Problem caused by MyClass having MyClass(const MyClass&) = delete; MyClass& operator=(const MyClass&) = delete; This is needed because MyClass holds unique_ptr objects and I generally want to avoid copy. But at this point my code has index access [] operator utilized, and I dont want to re write chucks of code. Is there a container in STD that is suitable? Edit: To people suggesting usage of move constructor, I've tried this: //MyClass(const MyClass&) = delete; //MyClass& operator=(const MyClass&) = delete; MyClass(MyClass&&) = default; but compiler(g++) still gives error: /usr/include/c++/11/bits/stl_algobase.h:405:25: error: use of deleted function ‘M::MyClass& M::MyClass::operator=(const M::MyClass&)’ 405 | *__result = std::move(*__first); | ~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~ saying: note: ‘M::MyClass& M::MyClass::operator=(const M::MyClass&)’ is implicitly declared as deleted because ‘M::MyClass’ declares a move constructor or move assignment operator or I should not use default keyword and actually define move constructor?
As std::unique_ptr<T> is a moveable and non-copyable type, any class with a std::unique_ptr<T> member will by default be moveable and non-copyable (as long as all of the other members are at least moveable). #include <memory> #include <utility> struct A { std::unique_ptr<int> ptr; }; int main() { A a; //A b = a; //Will not compile A c = std::move(a); // Perfectly legal } Therefore if you remove the copy contstructor, copy assignment operator, move constructor, and move assignment operator, then everything would work fine. Your type would not be copyable, and erasing from std::vector would work fine. Note: std::vector<T>::operator[] returns a reference to the element so no copy is performed at this step either (for T not equal to bool). If you want to explicitly = delete the copy semantics then you also have to = default both the move constructor and move assignment operator to keep the move semantics of the type. This is known as the rule of 5.
73,150,688
73,150,845
What does this C++ pointer syntax mean?
Say datais a direct pointer to the memory array used by a vector. What then, does &data[index] mean? I'm guessing data[index] is a pointer to the particular element of the array at position index, but then is &data[index]the address of that pointer?
Start with working out the types. Suppose data is a T*; a pointer to the first element of an array of T. Then data[index] is a T, and that T is an element of the array. And since data[index] is a T, &data[index] is a T*; it is a pointer to the array element data[index]. Also, if data is a pointer, data[index] is equivalent to *(data + index), so &data[index] is equivalent to &*(data + index), and the &* cancel each other out and you're left with &data[index] == data + index.
73,151,238
73,151,948
LNK1104 cannot open file 'libboost_regex-vc90-mt-gd-1_37.lib'
Hi my team developed some years ago an application which consists of c# windows forms and c++. All developers gone away and nobody knows how to compile the source code. Now it is my job trying to compile it to be able to develop it further. As I am not a real software developer (studied mechanical enginnering) and just learned C#, Javascript and Python I am facing huge problems. I am using Visual Studio 2022. As I am trying to compile the .sln I get the error "LNK1104 cannot open file 'libbost_regex-vc90-t-gd-1_37.lib'. Yesterday I have installed the boost library 1.79 with the "libboost_regex-vc143..." files in the installation folder. Next I tried to add the folder as "Additional Include Directories" and the "boost/stage" folder as "Additional Library Directories" as some answers on Stack Overflow suggested. After that I could succesfully run boost in a little test-project. In the Project folder of the application is a folder "c++/extern" with a folder called "boost" and I guess an old boost version with some files called "libboost-regex_vc80..". This folder is added as additional library in some projects of the application. I'm confused why do I get the error: "LNK1104 cannot open file 'libbost_regex-vc90-t-gd-1_37.lib' Neither my installed boost version nor the boost files in the "c++/extern" folder match this version. Why is Visual Studio searching for these files? Can somebody give me a hint how to solve this problem? (I can't share the source code) Thanks in advance
The name of the Boost library reflects a number of things. Specifically, libboost_regex-vc90-mt-gd-1_37.lib is the Boost Regex Library for Visual Studio 2008 (containing VC++ 9.0) MultiThreaded version 1.37 (i.e. Boost version) You downloaded VS2022, which explains why you got vc143 (VC++ 14.3). And you downloaded Boost 1.79 instead of 1.37 that was part of your project. The old 1.37 is so old that it doesn't know about VS2022. At this point, you're looking at rather big version changes. But it might not even be necessary. The boost regex library was standardized as <regex>, and that is included out of the box in VS2022. You don't need an extra library anymore.
73,151,255
73,171,127
clang error: cannot pass object of non-trivial type 'std::vector<long>' through variadic method; call will abort at runtime [-Wnon-pod-varargs]
I build with gcc,compile success,and run success! but when i build my repo with clang, i meet compile error! this is one error,other errors similar ./engine/dispatcher.h:74:57: error: cannot pass object of non-trivial type 'std::vector<long>' through variadic method; call will abort at runtime [-Wnon-pod-varargs] bool ret = (this->runner->*ins_func[func_i][dtype_i])(std::forward<Args>(args)...); many function calls this code template <class RunnerType> template <typename... Args> bool Dispatcher<RunnerType>::dispatcher(const int func_i, const int dtype_i, Args &&...args) { bool ret = (this->runner->*ins_func[func_i][dtype_i])(std::forward<Args>(args)...); } statement template <typename RunnerType> class Dispatcher { public: bool (RunnerType::*ins_func[INSTRUCTION_NUM][DTYPE_NUM])(...); } others related code template <typename RunnerType> void Dispatcher<RunnerType>::init_instructions_func() { ins_func[privpy::func::SAVE][privpy::dtype::INT8] = reinterpret_cast<bool (RunnerType::*)(...)>( &RunnerType::template save<int8_t, typename RunnerType::TypeSet::INUMT8>); ins_func[privpy::func::SAVE][privpy::dtype::INT16] = reinterpret_cast<bool (RunnerType::*)(...)>( &RunnerType::template save<int16_t, typename RunnerType::TypeSet::INUMT16>); } clang-version:14.0.0 os:ubuntu20.04 i write a demo to reproduce the problem,show the same error #include <iostream> #include <string> #include <vector> using namespace std; bool (*ins_func)(...); bool save(int a,vector<long> arr) { cout << a << endl; cout << " hello " << endl; return true; } template <typename T, typename... Args> bool sum_super_cool(T v, Args... args) { cout << "pre" << endl; bool ret = (*ins_func)(std::forward<Args>(args)...); return ret; } int main(int argc, char** argv) { ins_func = reinterpret_cast<bool (*)(...)>(&save); vector<long> arr; arr.push_back(123); sum_super_cool(1, 2, arr); return 0; } root@3e53105276e1:~/test/main# clang++-14 variable_arg.cpp -std=c++17 variable_arg.cpp:17:25: error: cannot pass object of non-trivial type 'std::vector<long>' through variadic function; call will abort at runtime [-Wnon-pod-varargs] bool ret = (*ins_func)(std::forward<Args>(args)...); ^ variable_arg.cpp:25:5: note: in instantiation of function template specialization 'sum_super_cool<int, int, std::vector<long>>' requested here sum_super_cool(1, 2, arr); ^ 1 error generated.
Why not also pass the function as a template parameter: #include <iostream> #include <string> #include <vector> bool save(int a, std::vector<long> arr) { std::cout << a << '\n'; std::cout << " hello \n"; return true; } template <typename T, typename Callable, typename... Args> bool sum_super_cool(T v, Callable ins_func, Args&&... args) { std::cout << "pre\n"; return ins_func(std::forward<Args>(args)...); } int main(int argc, char** argv) { std::vector<long> arr; arr.push_back(123); sum_super_cool(1, save, 2, arr); return 0; } This works fine without any reinterpret_casting voodoo. That should almost always be a giant red flag!
73,151,279
73,151,628
How do I initialize an object using a static member function of that object's class?
I have a class with some static functions. The class constructor takes a function as one of its arguments. template <typename T> class MyClass { public: static std::function<T(T, T)> func1 = [](T a, T b) { ... } static std::function<T(T, T)> func2 = [](T a, T b) { ... } MyClass(std::function<T(T, T)> func) { ... } } When I initialize an object from this class: MyClass<int> myObj(MyClass.func1); The compiler complains that: > argument list for class template "MyClass" is missing. What is the correct way to do this while keeping the functions in the class itself?
MyClass is a template not a class. The class that has a static member you want to pass to the constructor is MyClass<int>. Your code has some typos (missing ;), I had to add inline for in-class initialization of the static members, I introduced an alias, and for brevity I used struct rather than class (the class has only public members): #include <iostream> #include <functional> template <typename T> struct MyClass { using fun_t = std::function<T(T,T)>; static inline fun_t func1 = [](T a, T b) { return a+b; }; static inline fun_t func2 = [](T a, T b) { return a-b; }; fun_t fun; MyClass(std::function<T(T, T)> func) : fun(func) {} }; int main() { auto x = MyClass<int>{MyClass<int>::func1}; std::cout << x.fun(1,2); } As pointed out in comments by AyxanHaqverdili, this would work as well: auto x = MyClass{ MyClass<int>::func1 }; due to CTAD (class template argument deduction) where the class templates argument is deduced from the constructors parameters. Live Demo Also this is fine, although a bit hacky, and I don't recommend to actually use it: MyClass<int> x { x.func1 }; In a nutshell: You can refer to a variable in its own initializer. We aren't doing something that would require x to be fully initialized, so there is no problem with accessing the (already initialized) static member via an instance of MyClass<int>. Live Demo A less suspicious variant of this suggested by @HTNW is MyClass<int> x{decltype(x)::func1}; Now it is more obvious that we only use the type of x and access a static member of its class.
73,152,131
73,152,230
ESP home using Arduino library
I am about to write a custom ESPHome component. I don't have much experience with C language and I am facing some troubles using external library. For demonstration, I prepared a simple component class.. class Test: public Component { public: auto t = timer_create_default(); void setup() override { ESP_LOGD("TEST", "Test setup called!"); t.every(1000, TestLog); } void loop() override { ESP_LOGD("TEST", "Test loop called!"); t.tick(); } bool TestLog(void *) { ESP_LOGD("TEST", "TestLOG!"); return true; } } With this, I receive: In file included from src\main.cpp:32:0: src\Test.h:7:35: error: non-static data member declared 'auto' auto t = timer_create_default(); I took it from some example where they did not have the class, but I can't find out, how to use it. The library is: https://github.com/contrem/arduino-timer/ I can still rewrite it without this timer completely and handle it only in the loop function, but I would like to understand what I am doing wrong. If I change the return type to Timer<> I got another error: src\Test.h: In member function 'virtual void Test::setup()': src\Test.h:11:24: error: no matching function for call to 'Timer<>::every(int, )' t.every(1000, TestLog);
You can not use auto to declare non-static member variables so you need to replace auto with the type returned by timer_create_default(). If you are not sure what type it returns, you can simply use decltype in the declaration: decltype(timer_create_default()) t = timer_create_default(); If I read the code in the repo correctly, the returned type is Timer<>, so this should also work: Timer<> t = timer_create_default(); or simply: Timer<> t; Also: The function pointer passed to t.every() should be a bool (*)(void*) but TestLog is a non-static member function and the pointer type is bool (Test::*)(void*) - You can fix that by making TestLog static: class Test: public Component { public: // ... static bool TestLog(void *) { ESP_LOGD("TEST", "TestLOG!"); return true; } }; If you want to get the Test instance in the TestLog callback, make the Timer Timer<TIMER_MAX_TASKS, millis, Test*> t; and change TestLog: class Test: public Component { public: // ... static bool TestLog(Test* t) { ESP_LOGD("TEST", "TestLOG!"); return true; } }; and in setup(): t.every(1000, TestLog, this); You'll now get a pointer to the Test instance in the TestLog callback and you can use this to call a non-static member function in Test. Full example: class Test : public Component { public: Timer<TIMER_MAX_TASKS, millis, Test*> t; void setup() override { ESP_LOGD("TEST", "Test setup called!"); // call the static member function every second: t.every(1000, TestLogProxy, this); } void loop() override { ESP_LOGD("TEST", "Test loop called!"); t.tick(); } bool TestLog() { ESP_LOGD("TEST", "TestLOG!"); return true; } static bool TestLogProxy(Test* t) { // forward the callback call to the non-static member function: return t->TestLog(); } };
73,152,583
73,152,866
How to compare two downcasted object types in C++
I have two objects inheriting from Base class. Both are stored in vector: std::vector<Base*> m_vector; How can I check if the first type of object is equal to the second type of object? Scenarios: 1. First object type: A : public Base Second object type: B : public Base Result: Not equal First object type: A : public Base Second object type: A : public Base Result: Equal First object type: A : public Base Second object type: B : public A Result: Not equal
I am simplifying things a lot to get a point across. You have a std::vector<Base*> m_vector; This basically means: You have a vector of pointers to B. The actual objects are polymorphic, meaning you don't care what the actual type is as long as they inherit from B. Now you want to do something that requires you to know the actual type of the elements. Thats a contradiction. The easiest way to solve that contradiction is to give up the second point: Don't care what the actual type is, use only the interface defined in the base class. One way to do that is to use typeid. For example: #include <iostream> #include <typeinfo> #include <memory> #include <vector> struct Base { bool same_type(const Base& other) { return typeid(*this) == typeid(other); } virtual ~Base() = default; }; struct A : Base {}; struct B : Base {}; int main() { std::vector<std::unique_ptr<Base>> x; x.emplace_back(std::make_unique<A>()); x.emplace_back(std::make_unique<B>()); x.emplace_back(std::make_unique<B>()); std::cout << "expect 0 : " << (x[0]->same_type(*x[1])) << "\n"; std::cout << "expect 1 : " << (x[1]->same_type(*x[2])) << "\n"; } For details on typeid I refer you to https://en.cppreference.com/w/cpp/language/typeid. As suggested in a comment, you don't actually need to write a Base::same_type() but you can use typeid directly.
73,152,967
73,153,603
Why doesn't copy elision work in my static functional implementation?
I am trying to implement a "static" sized function, that uses preallocated store, unlike std::function that uses dynamic heap allocations. #include <utility> #include <cstddef> #include <type_traits> template <typename T, size_t StackSize = 64> class static_function; // TODO: move and swap // - can move smaller instance to larger instance // - only instances of the same size are swappable // TODO: condiotnal dynamic storage? template <typename Ret, typename ... Args, size_t StackSize> class static_function<Ret(Args...), StackSize> { public: constexpr static size_t static_size = StackSize; using return_type = Ret; template <typename Callable> constexpr explicit static_function(Callable &&callable) : pVTable_(std::addressof(v_table::template get<Callable>())) { static_assert(sizeof(std::decay_t<Callable>) <= static_size, "Callable type is too big!"); new (&data_) std::decay_t<Callable>(std::forward<Callable>(callable)); } constexpr return_type operator()(Args ... args) const { return (*pVTable_)(data_, std::move(args)...); } ~static_function() noexcept { pVTable_->destroy(data_); } private: using stack_data = std::aligned_storage_t<static_size>; struct v_table { virtual return_type operator()(const stack_data&, Args &&...) const = 0; virtual void destroy(const stack_data&) const = 0; template <typename Callable> static const v_table& get() { struct : v_table { return_type operator()(const stack_data &data, Args &&... args) const override { return (*reinterpret_cast<const Callable*>(&data))(std::move(args)...); } void destroy(const stack_data &data) const override { reinterpret_cast<const Callable*>(&data)->~Callable(); } } constexpr static vTable_{}; return vTable_; } }; private: stack_data data_; const v_table *pVTable_; }; However, it does not work as expected, since copies of the callable (copy elision does not kick in like in just lambda). Here is what is expected vs actiual behavior with -O3: #include <iostream> #include <string> int main() { struct prisoner { std::string name; ~prisoner() { if (!name.empty()) std::cout << name << " has been executed\n"; } }; std::cout << "Expected:\n"; { const auto &func = [captured = prisoner{"Pvt Ryan"}](int a, int b) -> std::string { std::cout << captured.name << " has been captured!\n"; return std::string() + "oceanic " + std::to_string(a + b); }; std::cout << func(4, 811) << '\n'; } std::cout << "THE END\n\n"; std::cout << "Actual:\n"; { const auto &func = static_function<std::string(int, int)>([captured = prisoner{"Pvt Ryan"}](int a, int b) -> std::string { std::cout << captured.name << " has been captured!\n"; return std::string() + "oceanic " + std::to_string(a + b); }); std::cout << func(4, 811) << '\n'; } std::cout << "THE END!\n"; return 0; } Output: Expected: Pvt Ryan has been captured! oceanic 815 Pvt Ryan has been executed THE END Actual: Pvt Ryan has been executed Pvt Ryan has been captured! oceanic 815 Pvt Ryan has been executed THE END! https://godbolt.org/z/zc3d1Eave What did I do wrong within the implementation?
It is not possible to elide the copy/move. The capture is constructed when the lambda expression is evaluated in the caller resulting in a temporary object. That lambda is then passed to the constructor and the constructor explicitly constructs a new object of that type in the storage by copy/move from the passed lambda. You can't identify the object created by placement-new with the temporary object passed to the constructor. The only way to resolve such an issue is by not constructing the lambda with the capture that should not be copied/moved in the caller at all, but to instead pass a generator for the lambda which is then evaluated by the constructor when constructing the new object with placement-new. Something like: template <typename CallableGenerator, typename... Args> constexpr explicit static_function(CallableGenerator&& generator, Args&&... args) : pVTable_(std::addressof(v_table::template get<std::invoke_result_t<CallableGenerator, Args...>>())) { static_assert(sizeof(std::decay_t<std::invoke_result_t<CallableGenerator, Args...>>) <= static_size, "Callable type is too big!"); new (&data_) auto(std::invoke(std::forward<CallableGenerator>(generator), std::forward<Args>(args)...); } //... const auto &func = static_function<std::string(int, int)>([](auto str){ return [captured = prisoner{str}](int a, int b) -> std::string { std::cout << captured.name << " has been captured!\n"; return std::string() + "oceanic " + std::to_string(a + b); }); }, "Pvt Ryan"); // or const auto &func = static_function<std::string(int, int)>([str="Pvt Ryan"]{ return [captured = prisoner{str}](int a, int b) -> std::string { std::cout << captured.name << " has been captured!\n"; return std::string() + "oceanic " + std::to_string(a + b); }); }); This requires C++17 or later to guarantee that the copy/move is elided. Before C++17 the elision cannot be guaranteed in this way with a lambda. Instead a manually-defined function object must be used so that its constructor can be passed the arguments like I am doing here with the generator. That would be the equivalent of emplace-type functions of standard library types.
73,153,462
73,153,537
How can I set class member variable correctly from vector in C++
I'm trying to set a class member variable from STL vector in C++. But it doesn't work the way I want it to. The variable doesn't change, The variable is the same like before. Am I programming in the wrong way? Here's the code. #include <iostream> #include <vector> using namespace std; class Test { private: std::string name; public: Test(); Test(std::string p_name); std::string getName(); void setName(std::string p_name); }; Test::Test() { name = ""; } Test::Test(std::string p_name) : name(p_name) {} std::string Test::getName() { return name; } void Test::setName(std::string p_name) { name = p_name; } int main() { // Initializing vector with values vector<Test> tests; for (size_t i = 0; i < 10; i++) { tests.push_back(Test()); } for (Test test : tests) { cout << test.getName() << endl; test.setName("a"); } for (Test test : tests) { cout << test.getName() << endl; } return 0; } This is the result: > ./main > Why It doesn't work, and how to fix it?
You're copying the elements from the vector each time you iterate through it in your loop. Try changing your code to something like this: for (auto& test : myTests) { test.setName("My new name"); } In this case, the ampersand (&) marks the variables as a reference, which means you can manipulate it directly. The way your code is written, you're using the copy-constructor to construce a new object. You can circumvent this, by adding something like: public: explicit Test(const Test&) = delete; to your class. This will prevent the copying of the object, which will reduce the likelihood of these types of errors.
73,153,748
73,153,850
type_info compiler bug in MSVC?
So I've got this code: #include <typeinfo> #include <iostream> void thing(char thing[2], int thing2) { } void thing2(char* thing, int thing2) { } template <typename T, typename U> struct are_types_same { constexpr operator bool() const noexcept { return false; } }; template <typename T> struct are_types_same<T, T> { constexpr operator bool() const noexcept { return true; } }; int main() { const std::type_info& info = typeid(thing); const std::type_info& info2 = typeid(thing2); std::cout << "typeid: " << (info == info2) << '\n'; std::cout << "are_types_same: " << are_types_same<decltype(thing), decltype(thing2)>{} << '\n'; } I was surprised to see that when comparing the type infos of the types in MSVC (x86, v19.32), the comparison yielded false, while the template specialization based comparison yielded true. I tried it on clang (x86-64, v14.0.0) and both yield true. I've heard that MSVC is terrible at the newer C++ stuff like templates and such, is that what's happening here? Does this count as a compiler bug? Is it worth reporting somewhere?
Does this count as a compiler bug? Yes, this seems to be a msvc bug which has been reported as: type_info yields incorrect result when comparing functions. The two functions do have the same type and the check info == info2 should yield true.
73,154,067
73,154,504
Problem when linking C++ functions from .so
I have the following folder structure in my HOME: - myproject/ + src/ + utilities.cpp + inc/ + Executor.hpp + utilities.hpp + lib/ + utilities.o + libutilities.so - other_project/ + main.cpp The utilities.hpp contains: #pragma once #ifndef UTILITIES_HXX #define UTILITIES_HXX #include <string> #include <iostream> #include <map> #include <vector> namespace myproject{ void readFromCSV(const std::string& filename,char delimiter,const int nlines,std::map<int,std::vector<std::string>> & csv_contents); } #endif and the utilities.cpp : #include "utilities.hpp" #include<fstream> #include<algorithm> #include<sstream> const std::string readFileIntoString(const std::string & path){ auto ss=std::ostringstream{}; std::ifstream input_file(path); if(!input_file.is_open()){ std::cout<<"Unable to open" << path; exit(0); } ss<<input_file.rdbuf(); return ss.str(); } void readFromCSV(const std::string& filename,char delimiter,const int nlines,std::map<int,std::vector<std::string>> & csv_contents){ std::string file_contents=readFileIntoString(filename); std::istringstream sstream(file_contents); std::vector<std::string> items; std::string record; int counter=0; while(std::getline(sstream,record)&&(counter<nlines)){ std::istringstream line(record); while(std::getline(line,record,delimiter)){ record.erase(std::remove_if(record.begin(), record.end(), isspace), record.end()); items.push_back(record); } csv_contents[counter]=items; items.clear(); counter++; } } For creating the libutilities.so I executed the following bash script in $HOME/myproject: g++ -I./inc -fPIC -c -o utilities.o src/utilities.cpp gcc -shared -o libutilities.so utilities.o mv libutilities.so lib/ mv utilities.o lib/ This compiles fine. So I want to use the utilities library in other_project/main.cpp: #include "Executor.hpp" #include "utilities.hpp" using namespace myproject; main(){ //variable declaration and definition readFromCSV(setFilename(PATH_INPUT,SUFFIX_INPUT,batch_index),';',batches,p); //other code } So when I compile this as: g++ -o main main.o -I$(HOME)/myproject/inc -L$(HOME)/myproject/lib -lutilities within the Makefile, I got the following error: /usr/bin/ld: main.o: in function `main()': /my_home_directory/other_project/main.cpp:168: undefined reference to myproject::readFromCSV(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, char, int, std::map<int, std::vector<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > >, std::less<int>, std::allocator<std::pair<int const, std::vector<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > > > >&)' pgacclnk: child process exit status 1: /usr/bin/ld Any idea? thanks
You declare the function readFromCSV in the namespace myproject and define the function readFromCSV in the global namespace. Thus you get the error undefined reference to myproject::readFromCSV.
73,154,194
73,154,446
How do I know which C++ source files include a specific h header file
I am studying a big C++ project and find a critical header file. I want to find all those .cpp files which include this header file to know the header file's influence scope. However I cannot find a simple way (several clicks or commands) to achieve this via vscode. Is there any trick can get this done? preferably using vscode. Example, say we have source code files a.cpp, b.cpp, c.cpp..., and a header file foo.h, how do I know which source code file include this foo.h without opening them and check one by one?
Try "Edit->Find in Files" option inside VSCode for the header file you are looking for. The search result will give you the desired answer.
73,154,241
73,154,592
Is there a way to test a self-written C++ semaphore?
I read the "Little Book Of Semaphores" by Allen B. Downey and realized that I have to implement a semaphore in C++ first, as they appear as apart of the standard library only in C++20. I used the definition from the book: A semaphore is like an integer, with three differences: When you create the semaphore, you can initialize its value to any integer, but after that the only operations you are allowed to perform are increment (increase by one) and decrement (decrease by one). You cannot read the current value of the semaphore. When a thread decrements the semaphore, if the result is negative, the thread blocks itself and cannot continue until another thread increments the semaphore. When a thread increments the semaphore, if there are other threads wait- ing, one of the waiting threads gets unblocked. I also used the answers to the question C++0x has no semaphores? How to synchronize threads? My implementation is a bit different from those by the link, as I unlock my mutex before notifying a thread on signalling and also the definition by the book is a bit different. So I implemented the semaphore and now I've realized that I don't know how I can really properly test it, except for the simplest case like e.g. sequentializing two calls for two threads. Is there any way to test the implementation like kinda using 100 threads or something like this and having no deadlock? I mean what test I should write to check the implementation? Or if the only way to check is to look through the code attentively, could you, maybe, please check? My implementation: // semaphore.h #include <condition_variable> #include <mutex> namespace Semaphore { class CountingSemaphore final { public: explicit CountingSemaphore(int initialValue = 0); void signal(); void wait(); private: std::mutex _mutex{}; std::condition_variable _conditionVar{}; int _value; }; } // namespace Semaphore // semaphore.cpp #include "semaphore.h" namespace Semaphore { CountingSemaphore::CountingSemaphore(const int initialValue) : _value(initialValue) {} void CountingSemaphore::signal() { std::unique_lock<std::mutex> lock{_mutex}; ++_value; if (0 == _value) { lock.unlock(); _conditionVar.notify_one(); } } void CountingSemaphore::wait() { std::unique_lock<std::mutex> lock{_mutex}; --_value; if (0 > _value) { _conditionVar.wait(lock, [this]() { return (0 <= this->_value); }); } } } // namespace Semaphore
This code is broken. Your current state machine uses negative numbers to indicate a number of waiters, and non-negative indicates remaining capacity (with 0 being no availability, but no waiters either). Problem is, you only notify waiters when the count becomes zero. So if you had a semaphore with initial value 1 (basically a logical mutex), and five threads try to grab it, one gets it, and four others wait, at which point value is -4. When the thread that grabbed it finishes and signals, value rises to -3, but that's not 0, so notify_one is not called. In addition, you have some redundant code. The predicate-based form of std::condition_variable's wait is equivalent to: while (!predicate()) { wait(lock); } so your if check is redundant (wait will check the same information before it actually waits, even once, anyway). You could also condense the code a bit by having the increment and decrement on the same line you test them (it's not necessary since you're using mutexes to protect the whole block, not relying on atomics, but I like writing threaded code in a way that would be easier to port to atomics later, mostly to keep in the habit when I write actual atomics code). Fixing the bug and condensing the code gets this end result: void CountingSemaphore::signal() { std::unique_lock<std::mutex> lock{_mutex}; if (0 >= ++_value) // If we were negative, had at least one waiter, notify one of them; personally, I'd find if (value++ < 0) clearer as meaning "if value *was* less than 0, and also increment it afterwards by side-effect, but I stuck to something closer to your design to avoid confusion { lock.unlock(); _conditionVar.notify_one(); } } void CountingSemaphore::wait() { std::unique_lock<std::mutex> lock{_mutex}; --_value; _conditionVar.wait(lock, [this]() { return 0 <= this->_value; }); } The alternative approach would be adopting a design that doesn't drop the count below 0 (so 0 means "has waiters" and otherwise the range of values is just 0 to initialValue). This is safer in theoretical circumstances (you can't trigger wraparound by having 2 ** (8 * sizeof(int) - 1) waiters). You could minimize that risk by making value a ssize_t (so 64 bit systems would be exponentially less likely to hit the bug), or by changing the design to stop at 0: // value's declaration in header and argument passed to constructor may be changed // to an unsigned type if you like void CountingSemaphore::signal() { // Just for fun, a refactoring to use lock_guard rather than unique_lock // since the logical unlock is unconditionally after the value read/modify int oldvalue; // Type should match that of value { std::lock_guard<std::mutex> lock{_mutex}; oldvalue = value++; } if (0 == oldvalue) _conditionVar.notify_one(); } void CountingSemaphore::wait() { std::unique_lock<std::mutex> lock{_mutex}; // Waits only if current count is 0, returns with lock held at which point // it's guaranteed greater than 0 _conditionVar.wait(lock, [this]() { return 0 != this->_value; }); --value; // We only decrement when it's positive, just before we return to caller } This second design has a minor flaw, in that it calls notify_one when signaled with no available resources, but no available resources might mean "has waiters" or it might mean "all resources consumed, but no one waiting". This isn't actually a problem logically speaking though; calling notify_one with no waiters is legal and does nothing, though it may be slightly less efficient. Your original design may be preferable on that basis (it doesn't notify_one unless there were definitely waiters).
73,154,797
73,155,569
What is the meaning of Conan Revision on Conan Center?
On Conan Center, there are 6 revisions of boost/1.79.0, but when I look at the "List of available binary packages" section, I can see a list longer than 6. Each binary package contains a unique set of settings, aka revisions. What is meant by Revision 6? https://conan.io/center/boost?tab=configuration&os=Linux
Revisions are changes to the recipe itself (i.e. changes to the conanfile.py or other parts of the recipe). The revisions will be to fix bugs, add more options or add newer versions of boost. You can see the changes at https://github.com/conan-io/conan-center-index/commits/master/recipes/boost Each revision of the recipe is then built with multiple settings and platforms to produce many binary packages.
73,155,027
73,155,067
Why is a bit-wise AND necessary to check if a bit is set?
I am learning a backtrack problem with memoization using bit-mask. When checking if the i'th bit is set in a bit-mask, all the solutions I have come across are doing (mask >> i) & 1. I was wondering, why is the & 1 necessary? Isn't (mask >> i) a 1 when the i'th bit is set, and a 0 when the bit is not set? That already translate into true and false.
(mask >> i) cannot eliminate the higher bits. For example, when mask = 5 (101 in binary) and i = 1, the value of (mask >> i) is 2. This evaluated as true, but the 2nd lowest bit is 0, so you fail to check the bit correctly. Therefore, & 1 is necessary to eliminate the higher bits and check one specified bit correctly.
73,155,255
73,208,822
QT C++ All datas shown on same column when export csv?
I want to save a set of data in csv file. I have no problem with registration. My problem is in the form of saving. All data are collected in column A. I have 2 graphs in total, graph1 and graph2. Graph1 should be in column A and Graph2 should be in column B. How can I set this up. Here is code for export csv void MainWindow::exportArraysToCSV(QStringList labelList, QList < QList < double >> dataColums, QChar sep) { QString filters("CSV files (*.csv);;All files (*.*)"); QString defaultFilter("CSVi files (*.csv)"); QString fileName = QFileDialog::getSaveFileName(0, "Save file", QCoreApplication::applicationDirPath(), filters, & defaultFilter); QFile file(fileName); if (file.open(QFile::WriteOnly | QFile::Append)) { QTextStream data( & file); QStringList strList; foreach(auto label, labelList) { if (label.length() > 0) strList.append("\"" + label + "\""); else strList.append(""); } data << strList.join(",") << "\n"; int maxRowCount = 0; foreach(auto column, dataColums) maxRowCount = qMax(maxRowCount, column.count()); for (int i = 5; i < maxRowCount; ++i) // rows { strList.clear(); for (int j = 0; j < 2; ++j) // columns { if (i < dataColums[j].count()) strList.append(QString::number(dataColums[j][i], 'f')); else strList.append("\"\" "); } data << strList.join(";") + "\n"; } file.close(); } } I think this code for join all data on same column. How can I split it? data << strList.join(",") << "\n"; Here is write log to csv function void Logger::writeLogCSV(QStringList labelList, QList<double> dataList, bool addTime) { QTextStream out(logFile); if (addTime) { if (csvLabelsBuffer.contains("time") == false) csvLabelsBuffer.insert(0, "time"); } if (labelList.count() == 0) { qDebug() << "Empty label list - abort csv write"; return; } bool canAddLabel = false; for (auto i = 2; i < labelList.count(); ++i) { if (csvLabelsBuffer.count() == 2 || csvLabelsBuffer.contains(labelList[i]) == false) { canAddLabel = true; csvLabelsBuffer.append(labelList[i]); } } if (canAddLabel) { canAddLabel = false; QStringList origFile = out.readAll().split(QRegExp("[\r\n]"), QString::SplitBehavior::SkipEmptyParts); for (auto i = 2; i < csvLabelsBuffer.count(); ++i) out << "\"" + csvLabelsBuffer[i] + "\t"; out << ""; // out << "\n"; if (origFile.length() > 0) { while (origFile.first().contains("\"")) origFile.removeFirst(); } logFile->resize(0); // delete contents ! for (auto i = 2; i < origFile.count(); ++i) // Start from second line (data without first line which contains labels) out << origFile[i] + ","; return; } // add Data ! for (auto i = 2; i < csvLabelsBuffer.count(); ++i) { out.atEnd(); // ??? int index = labelList.indexOf(csvLabelsBuffer[i]); if (index >= 0 && index < dataList.count()) out << QString::number(dataList[index], 'f') + ","; else if (csvLabelsBuffer[i] == "time") out << QDateTime::currentDateTimeUtc().toString("yyyy-MM-ddTHH:MM:ss.zzzZ") + ','; } out << "\n \n"; }
you should open the generated file with a text editor and post some lines of it here to your answer. By Opening the File with excel you need to set the seperator it will use to split the the row into columns. Usually it will use ',' but sometimes it will default to ';'. this will seperate them by comma, which is the standard for csv: void MainWindow::exportArraysToCSV(QStringList labelList, QList < QList < double >> dataColums, QChar sep) { QString filters("CSV files (*.csv);;All files (*.*)"); QString defaultFilter("CSVi files (*.csv)"); QString fileName = QFileDialog::getSaveFileName(0, "Save file", QCoreApplication::applicationDirPath(), filters, & defaultFilter); QFile file(fileName); if (file.open(QFile::WriteOnly | QFile::Append)) { QTextStream data( & file); QStringList strList; foreach(auto label, labelList) { if (label.length() > 0) strList.append("\"" + label + "\""); else strList.append(""); } data << strList.join(",") << "\n"; int maxRowCount = 0; foreach(auto column, dataColums) maxRowCount = qMax(maxRowCount, column.count()); for (int i = 5; i < maxRowCount; ++i) // rows { strList.clear(); for (int j = 0; j < 2; ++j) // columns { if (i < dataColums[j].count()) strList.append(QString::number(dataColums[j][i], 'f')); else strList.append("\"\" "); } data << strList.join(",") + "\n"; } file.close(); } } If that does not fix your problem, then you need to open your csv with a texteditor and see whats wrong with it. Post some lines of it here then.
73,155,412
73,155,464
Optimized string storage for static strings
I know that in C/C++, if you write a string literal, this is actually placed into read-only memory with static (lifetime of the program) storage. So, for example: void foo(const char* string) { std::cout << static_cast<void const*>(string) << std::endl; } int main() { foo("Hello World"); } should print out a pointer to someplace in read-only memory. Here's my question, let's say I want to write a copy-on-write String class which has an optimization for static data like this. Instead of copying the whole string into dynamically-allocated memory (which is expensive), why not just keep a pointer to the static data instead. Then, if a write actually does need to occur, then I can make a copy at that point. But how can I tell if a string is static or something like: int main() { char[] myString = "Hello World"; foo(myString); } In this case, myString is located in the stack and not the heap, thus it's lifetime is not static. My first thought was a special constructor for std::string_view, but I'm not sure that std::string_view implies a string with static lifetime either...
The easiest way I can think of is to do it with a user-defined literal operator. struct cow_string { /* stuff */ }; cow_string operator "" _cow( const char*, size_t ); Then, when someone does: cow_string betsy = "moo"_cow; the argument to operator""_cow is guaranteed to be a static string. I mean, barring pathological cases like someone invoking operator"" directly by name (which I honestly don't even know if it is possible; if it is and you do it and it breaks stuff, well, you deserve whatever happens).
73,155,522
73,155,623
OpenGL doesn't draw a point
OpenGL draws only the background, the yellow point does not appear. I want to draw it with glBegin and glEnd. The coordinates are variables, because I want to move that point later. Most of the code is just GLFW initialization the function that worries me is the draw_player function since there the draw call is contained. The Fix I stumbled upon, to use GL_POINTS instead of GL_POINT (in glBegin as argument), does not help (I continue to use it though). #include <GLFW/glfw3.h> //#include <stdio.h> //coordinates int px, py; //My not working function void draw_player() { glColor3f(1.0f, 1.0f, 0); glPointSize(64.0f); glBegin(GL_POINTS); glVertex2i(px, py); glEnd(); } int main(int argc, char* argv[]) { GLFWwindow* window; if (!glfwInit()) return -1; window = glfwCreateWindow(910, 512, "Raycast", NULL, NULL); if (!window) { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glClearColor(0.1f, 0.1f, 0.5f, 1.0f); //setting the coordinates px = 100; py = 10; while (!glfwWindowShouldClose(window)) { /* Render here */ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); draw_player(); /* Swap front and back buffers */ glfwSwapBuffers(window); /* Poll for and process events */ glfwPollEvents(); } glfwTerminate(); return 0; }
The coordinate (100, 10) is not in the window. You have not specified a projection matrix. Therefore, you must specify the coordinates of the point in the normalized device space (in the range [-1.0, 1.0]). If you want to specify the coordinates in pixel units, you must define a suitable orthographic projection with glOrtho: int main(int argc, char* argv[]) { GLFWwindow* window; if (!glfwInit()) return -1; window = glfwCreateWindow(910, 512, "Raycast", NULL, NULL); if (!window) { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glMatrixMode(GL_PROJECTION); glOrtho(0, 910.0, 512.0, 0.0, -1.0, 1.0); glMatrixMode(GL_MODELVIEW); // [...] }
73,156,198
73,156,345
Eigen matrix template alias
I had a class definition that compile with VS C++ 20 and not with g++-11 It just consist in an overload of the Eigen Matrix class to define a Vector type. with g++ the compiler says: error: wrong number of template arguments (1, should be at least 3) using BaseVector = Eigen::Matrix< typename T, Eigen::Dynamic, 1, Eigen::StorageOptions::AutoAlign, Eigen::Dynamic, 1 >; while compiling the following, and it put the error mark just before the last >: template<typename T> class Vector : public Eigen::Matrix<T, Eigen::Dynamic, 1, Eigen::StorageOptions::AutoAlign> { public: using BaseVector = Eigen::Matrix< typename T, Eigen::Dynamic, 1, Eigen::StorageOptions::AutoAlign, Eigen::Dynamic, 1 >; ......etc..... any idea will be welcome, to explain that compiler error, I already try typedef i.s.o the using (alias) but it's coming from something else !
Its a combination of MSVC accepting typename in a place where it does not belong and gcc producing a rather confusing error message. 1, should be at least 3 ?!? Probably it gets stuck at typename T, stops there and reports the wrong error. Remove typename (T is not a dependant name): #include "Eigen/Dense" template<typename T> class Vector : public Eigen::Matrix<T, Eigen::Dynamic, 1, Eigen::StorageOptions::AutoAlign> { public: using BaseVector = Eigen::Matrix<T, Eigen::Dynamic, 1, Eigen::StorageOptions::AutoAlign, Eigen::Dynamic, 1 >; }; Live gcc11
73,157,920
73,158,471
Undefined behavior (according to clang -fsanitize=integer) on libstdc++ std::random due to negative index on Mersenne Twister engine
I'm using clang++ 10 on Ubuntu 20.04 LTS, with -fsanitize-undefined-trap-on-error -fsanitize=address,undefined,nullability,implicit-integer-truncation,implicit-integer-arithmetic-value-change,implicit-conversion,integer My code is generating random bytes with std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<uint8_t> dd(0, 255); ... ch = uint8_t(dd(gen)); This last line causes the sanitizer to report undefined behavior is in bits/random.tcc template<...> void mersenne_twister_engine<...>:: _M_gen_rand(void) { const _UIntType __upper_mask = (~_UIntType()) << __r; const _UIntType __lower_mask = ~__upper_mask; for (size_t __k = 0; __k < (__n - __m); ++__k) { _UIntType __y = ((_M_x[__k] & __upper_mask) | (_M_x[__k + 1] & __lower_mask)); _M_x[__k] = (_M_x[__k + __m] ^ (__y >> 1) ^ ((__y & 0x01) ? __a : 0)); } for (size_t __k = (__n - __m); __k < (__n - 1); ++__k) { _UIntType __y = ((_M_x[__k] & __upper_mask) | (_M_x[__k + 1] & __lower_mask)); _M_x[__k] = (_M_x[__k + (__m - __n)] ^ (__y >> 1) <<<<===== this line ^ ((__y & 0x01) ? __a : 0)); } _UIntType __y = ((_M_x[__n - 1] & __upper_mask) | (_M_x[0] & __lower_mask)); _M_x[__n - 1] = (_M_x[__m - 1] ^ (__y >> 1) ^ ((__y & 0x01) ? __a : 0)); _M_p = 0; } The error reads: /usr/include/c++/10/bits/random.tcc:413:33: runtime error: unsigned integer overflow: 397 - 624 cannot be represented in type 'unsigned long' SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/include/c++/10/bits/random.tcc:413:33 in /usr/include/c++/10/bits/random.tcc:413:26: runtime error: unsigned integer overflow: 227 + 18446744073709551389 cannot be represented in type 'unsigned long' SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/include/c++/10/bits/random.tcc:413:26 in It appears that there is a difference __m-__n == 397 - 624 that is obviously negative but the operands are all unsigned. The variables being subtracted are template parameters defined as size_t __n, size_t __m so this is not a random edge case, it's the actual template being implemented. Is this a bug in this implementation of the STL or my usage is wrong? A minimal reproducible example: https://godbolt.org/z/vvjWscPnj UPDATE: Issue (not a bug) filed to GCC https://gcc.gnu.org/bugzilla/show_bug.cgi?id=106469 - closed as "WONT FIX" GCC's team called clang's ubsan unsigned integer overflow checks bad practice, because the behaviour is well-defined (as modulo wrapping) in ISO C++. Although modulus arithmetic is used in PRNG, this is not the case in this particular case. However in most userspace code a unsigned overflow is almost all the time a bug to be caught and this non-bug on the GCC's STL prevents users from benefitting from this useful check.
Although as the other answer indicates it is undefined behavior per standard to instantiate std::uniform_int_distribution with uint8_t template argument, the UBsan warning here is unrelated to that. UBSan is flagging the implementation of the Mersenne twister itself, but the implementation doesn't have any undefined behavior or bug. If you look closely you see that the offending expression is _M_x[__k + (__m - __n)] where __k is a value in the range from (__n - __m) to (__n - 1) via the for loop. All of the types involved in these operations are std::size_t which is unsigned. As a consequence these operations all use modular arithmetic and therefore even if __m - __n is negative and not representable in the unsigned type, the result of __k + (__m - __n) will lie between 0 and __m - 1, so that indexing the array with it is not a problem. No undefined behavior, unspecified behavior or implementation-defined behavior is involved. The UBSan check which is flagging this is not flagging actual undefined behavior. It is perfectly ok to rely on the wrap-around behavior of unsigned arithmetic like this if one is aware of it. The unsigned overflow check is only meant to be used to flag instances of such wrap-around where it was not intentional. You shouldn't use it on other's code that might rely on it or on your own code if you might be relying on it. In -fsanitize=address,undefined,nullability,implicit-integer-truncation,implicit-integer-arithmetic-value-change,implicit-conversion,integer all except address and undefined enable UBsan checks which are not flagging actual undefined behavior, but conditions that may be unintentional in many cases. The default -fsanitize=undefined sanitizer flag doesn't enable the unsigned integer overflow check by default for the reasons given above. See https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html for details.
73,158,173
73,174,012
Is there a way to make VS Code stop highlighting C++ errors without disabling the extension?
Please, help me. I need VSCode to stop highlight (underline) errors in C++ (.ino files). I am trying to code a firmware for Arduino board but its highlighting, for example pinMode() as error (not defined) even if both Arduino and Arduino snippets extensions are installed and enabled. I already tried to set problems.decoration.enabled to false, but it did not fix my problem. I can't uninstall or disable C/C++ extension because that is what Arduino extension depends on. Can someone please help me fix this? Thanks.
Go to Files -> Preferences -> Settings -> Here you can disable the relevent IntelliSense suggestions.
73,158,228
73,158,799
Clang can't find C++ module with `-fprebuilt-module-path`
I have two files, main.cc and S.cc, in the same directory. S.cc contains a module named S_mod. When compiling I get an error about S_mod not being found despite using -fprebuilt-module-path=.. I've tried creating a separate directory for the *.pcm files but that had no effect. main.cc: import S_mod; int main() { return 0; } S.cc: export module S_mod; export struct S { int x, y; }; clang++ -std=c++20 -fmodules-ts -fprebuilt-module-path=. --precompile -x c++-module S.cc -o S.pcm clang++ -std=c++20 -fmodules-ts -fprebuilt-module-path=. -c S.pcm -o S.o clang++ -std=c++20 -fmodules-ts -fprebuilt-module-path=. S.o main.cc -o test main.cc:3:8: fatal error: module 'S_mod' not found import S_mod; ~~~~~~~^~~~~ 1 error generated.
For the following, I added some output to your main.cc so it looks like this, to demonstrate it's all working. import S_mod; #include <iostream> int main() { S s = { 1, 2 }; std::cout << s.x << " " << s.y << std::endl; return 0; } You need to make sure all the names of your module artifacts are correct. For you, main.cc expects to find S_mod, and by default, Clang expects to find something named S_mod.pcm for compilation. So, for example, this set of commands would work correctly because you'd be outputting a .pcm file with the same name as the module you're trying to import. clang++ -std=c++20 -fmodules-ts --precompile -x c++-module S.cc -o S_mod.pcm clang++ -std=c++20 -fmodules-ts -c S_mod.pcm -o S_mod.o -fprebuilt-module-path=. clang++ -std=c++20 -fmodules-ts -fprebuilt-module-path=. main.cc -o test ./test 1 2 Alternatively, you can specify -fmodule-file which allows you to specify the mapping of module_name=module_file. clang++ -std=c++20 -fmodules-ts --precompile -x c++-module S.cc -o S.pcm clang++ -std=c++20 -fmodules-ts -c S.pcm -o S.o # Notice that we map S_mod=S.pcm - you could just say S.pcm but # then clang will always load the module file regardless of whether # or not it needs to clang++ -std=c++20 -fmodules-ts -fprebuilt-module-path=. -fmodule-file="S_mod=S.pcm" main.cc -o test ./test 1 2
73,158,620
73,158,703
Specialize class templated on constrained non-type parameter
Let's consider the following code for compile-time evaluation of the factorial function: #include <concepts> template <std::integral auto num> struct factorial { constexpr static auto val{num * factorial<num - 1>::val}; }; // Note: This only specializes the class for (int)0 template <> struct factorial<0> { constexpr static auto val{1}; }; // ... factorial<4>::val; // Ok: 24 factorial<4u>::val; // error: template instantiation depth exceeds maximum of 900 // This makes sense: There's no factorial<0u> specialization. Is there a way to introduce specialization factorial<0> for all integral types (i.e. for all the types that satisfy std::integral)? Of course, I'd like to avoid actually writing out specializations factorial<0u>, factorial<0l>, and so on.
Instead of explicitly specializing for specifically 0 (i.e. an int with value 0), you can partially specialize for any value which compares equal to 0: template <std::integral auto I> requires (I == 0) struct factorial<I> { static constexpr auto val = 1; }; which if you prefer can also be spelled this way: template <class T, T I> requires (I == 0) struct factorial<I> { static constexpr auto val = 1; }; but I don't think there's a way to deduce T{0} as the value.
73,158,775
73,160,895
Why do I import std.core but not std?
I did the steps described here with MSVC2022 and was able to do: import std.core; but not import std; what is the difference? What is this std.core?
I suggest you read this issue carefully, the problem is similar to yours. And usually, In MSVS std refers to namespace, you could use the contents of std by adding using namespace std;, such as std::cout, etc.
73,158,786
73,158,894
Locking an array of std::mutex using a std::lock_guard array
I have the following array of mutexes: std::mutex mtx[5]; And I would like to lock them all with an RAII style: std::lock_guard<std::mutex> grd[5] { mtx[0], mtx[1], mtx[2], mtx[3], mtx[4] }; While the above code works, it isn't ideal as I can't write it independently of the size of the array (here 5). Is there a way to do that? Shall I work with template magic to create an std::initializer_list out of an array? (is that possible?) I'm open to using std::array or std::vector instead of C-style arrays, I used those here for conciseness. Ideally this works in C++14 but any solution up to latest standards is fine.
What you want is std::scoped_lock. It takes N mutexes and locks them on creation and unlocks on destruction. That would give you std::scoped_lock sl{mtx[0], mtx[1], mtx[2], mtx[3], mtx[4]}; If that's still too verbose you can wrap that in a factory function like // function that actually creates the lock template<typename Mutexes, std::size_t N, std::size_t... Is> auto make_scoped_lock(Mutexes (&mutexes)[N], std::index_sequence<Is...>) { return std::scoped_lock{mutexes[Is]...}; } // helper function so you don't have to create your own index_sequence template<typename Mutexes, std::size_t N> auto make_scoped_lock(Mutexes (&mutexes)[N]) { return make_scoped_lock(mutexes, std::make_index_sequence<N>{}); } int main() { std::mutex mtx[5]; auto lock = make_scoped_lock(mtx); } If you switch to using a std::array to hold the mutexes then the code can be simplified to a call to std::apply to do the expansion of the array into a parameter pack like template<typename Mutexes> auto make_scoped_lock(Mutexes& mutexes) { return std::apply([](auto&... mutexes) { return std::scoped_lock{mutexes...}; }, mutexes); } int main() { std::array<std::mutex, 5> mtx; auto sl = make_scoped_lock(mtx); }
73,158,957
73,159,034
Is Visual C++ SEH available on other OS?
I learned about Visual C++ Structured Exception Handling (SEH) recently. I am considering implementing it, but my code is supposed to be as cross platform as possible. In the future, I'm thinking of porting ny code to Linux, MAC, Android, IOS and potentially consoles. Is SEH something that can work on all of these platforms?!
SEH is a Microsoft-specific extension. Clang-cl has partial support for SEH (on Windows platforms), which could presumably be adapted for use on other OSes, but it wouldn’t be straightforward and it wouldn’t offer support for the sorts of things you can catch with SEH but not standard C++ extensions. Don’t use SEH if you want to write platform-independent code.
73,158,968
73,158,991
Why are 'top' and 'pop' seen as undeclared identifiers when I subclass the STL stack class?
I'm feeling rather stupid - must be missing something silly --- I wanted to subclass the generic STL stack class so that I could extend it with a combined top followed by pop operation but my compiler is telling me that both top and pop are undeclared identifiers. template <typename T> class MyStack : public stack<T> { public: T PopTop() // Convenience - combined top and pop in one go { T result = top(); pop(); return result; } }; I note that I can fix this problem by writing T result = stack<T>::top(); but why isn't top seen automatically given the stack class is directly inherited? Thanks in advance
First, don't descend from std classes, rather use private member (composition) and delegate functions - that's a common warning. With that said, the error is because a base class with a template argument is not considered in ADL lookup regarding the descendant class. You might have using stack<T>::pop; and similar declarations for each function that you plan to use in MyStack.
73,159,026
73,159,820
How to reduce compilation time with GLM?
I'm using GLM, which is a library that provides some low level math types and functions I use everywhere. But using this Visual Studio addon revealed that GLM comprises about 50% of my compilation time, or around 30 seconds, during each build. The documentation mentions using "precompiled headers" to speed up compilation, but I'm extremely unfamiliar with the concept, and haven't been able to find any further information on them. How might I get GLM to use precompiled headers? Would that alleviate the compilation time at all? I do know how to create a static library .lib file, but I'm unsure if that'd be useful at all for a header/template heavy library. (I also have trouble with chrono and mutex consuming a lot of time. Maybe that's just a cost that has to be paid though? I've done my best to restrict the compilation units they're included into at least.)
(Submitting an answer so others know what I did, but credit to @john for answering in the comments) Precompiled Headers got my build time down from 2 minutes to 10 seconds(!) In order to utilize "precompiled headers" in Visual Studio from an empty project, the steps I followed were: Add a pch.h and pch.cpp file to the project. In the properties of pch.cpp, under C++ -> precompiled header, set it to Create (/Yc) and set the the name of header file to pch.h (you can pick your own name if you want, stdafx.h and pch.h are just default names Visual Studio will pick.) pch.cpp should have #include "pch.h" as it's only line. This compilation unit will be compiled first and generates the compiler state all the other compilation units can now reuse. In the properties of every *.cpp file that you want to benefit from the precompiled header (it doesn't need to be all of them), you must go into their properties (ctrl+click or drag to do this for multiple files at once), and under C++ -> precompiled header set it to Use (/Yu) and use the same pch.h header name. Every source file you set to use a precompiled header, must include pch.h as it's very first action. This is because when the compiler encounters that line, it'll discard it's current state (everything before #include "pch.h") and use the state it generated when it compiled the pch.cpp unit. Finally, put all the headers and code you want to precompile into pch.h and that should be it. For me, my pch.h header ended up looking like this: #pragma once #include <vector> #include <string> #include <map> #include <queue> #include <mutex> #include <chrono> #include <atomic> #include <condition_variable> #include <cstdint> #include <cstdarg> #include <cctype> #include <cstring> #include <cstdlib> #include <utility> #include <cmath> #define GLM_FORCE_RADIANS #define GLM_FORCE_LEFT_HANDED #define GLM_ENABLE_EXPERIMENTAL #include <glm/glm.hpp> #include <glm/detail/func_common.hpp> #include <glm/trigonometric.hpp> #include <glm/gtc/constants.hpp> #include <glm/gtc/bitfield.hpp> #include <glm/gtc/round.hpp> #include <glm/gtx/rotate_vector.hpp> #include <glm/gtx/vector_angle.hpp> #include <glm/gtx/quaternion.hpp> Please note that I'm not speaking from authority on the subject though, just putting what I did for myself here if it's useful; I wouldn't be surprised if there were a more elegant way to do this.
73,159,092
73,159,126
How to test if a user inputted string is valid in do/while loop?
So essentially, I am asking the user for a departure time, as well as if it is in the AM or PM. In the code provided, I only test for AM/am (caps or lowercase), but in my actual program I will be testing for both AM/am and PM/pm. Now, when I set my do/while loop up like this: do { cout << "Please Enter a Valid Period: "; cin >> departure_amOrPM; } while (departure_amOrPM != "AM"); it works just fine, and it lets the program continue when "AM" is entered in all caps. But when I add another test to my loop like this: do { cout << "Please Enter a Valid Period: "; cin >> departure_amOrPM; } while (departure_amOrPM != "AM" || departure_amOrPM != "am"); it does not work. I tried entering both "AM" and "am", yet it did not let me continue. I don't know how to overcome this obstacle, so any help or tips would be much appreciated. Thanks!
Think about this condition } while (departure_amOrPM != "AM" || departure_amOrPM != "am"); This condition is true of every string. Every string is either not equal to "AM" or not equal to "am" (most strings are not equal to both). That's why you couldn't proceed. What you meant to write is this } while (departure_amOrPM != "AM" && departure_amOrPM != "am"); It's very common to get && and || confused, especially when also dealing with negation.
73,159,440
73,159,501
C++ dependency injection through constructor
I tried making a simple DI test, where a class car is injected with a container interface. It gives an error 'incomplete type', see the comment in the code. What am I doing wrong? #include <iostream> #include <string> class Car; class IContainer { public: virtual ~IContainer()=default; }; class Container: public IContainer { public: explicit Container(int i = 1) { std::cout << std::to_string(i); }; void makeCar() { Car car(this); //Variable has incomplete type 'Car' } }; class Car { public: explicit Car(IContainer &container): c(container) { printf("constructed\n"); } private: IContainer &c; }; int main() { Container container(5); container.makeCar(); return 0; } Solution - here's the working modified code: #include <iostream> #include <string> class Car; class IContainer { public: virtual ~IContainer()=default; virtual void foo(){} }; class Container: public IContainer { public: explicit Container(int i = 1) { std::cout << std::to_string(i) << std::endl; }; void foo() override { std::cout << "bar\n"; } void makeCar(); }; class Car { public: explicit Car(IContainer *container): c(container) { printf("Car constructed\n"); c->foo(); } private: IContainer *c; }; void Container::makeCar() { //Constructing the car will call a function on the injected container Car car(this); } int main() { Container container(5); container.makeCar(); return 0; }
Your C++ compiler reads your C++ program from beginning to the end, compiling as it goes along. At any point your C++ compiler only knows what it's read so far (we'll ignore some specific exceptions that do not matter here). class Car; Your C++ compiler now knows that your program has a class named Car. It doesn't know anything at all about this class. Nothing. Zilch. Nada. Zippo. void makeCar() { Car car(this); } Now your C++ compiler needs to generate code that creates such a Car. That's a problem: your C++ compiler doesn't know anything at all about this class. Nothing. Zilch. Nada. Zippo. The complete class gets declared later, but your C++ compiler doesn't know anything about it. The solution is simple: just declare the class method here: void makeCar(); And then later, after Car is declared, you can define this class method (just before main): void Container::makeCar() { Car car(this); // It works! } Everything else remains the same. Now your C++ compiler is omnipotent, all-knowing, and all-powerful. It knows everything now.
73,159,529
73,159,588
What does this code do? (A question about rvalue references)
So I was reading "The C++ Programming Language" and this code got shown. How does it exactly work? I tried asking elsewhere, watching a video on references and another one on basic move semantics but I'm still insanely confused. template<typename T> void swap(T& a, T& b) { T tmp {static_cast<T&&>(a)}; a = static_cast<T&&>(b); b = static_cast<T&&>(tmp); }
This is used in order to employ move semantics, if possible, with these objects. If move semantics are not possible then this automatically devolves to plain, garden-variety, copy-based swapping. The capsule summary is as follows. If you look at plain, garden-variety swapping: T tmp{a}; a=b; b=t; If these objects are "heavy" there's going to be a lot of copying going on. When you say a=b in C++, you are making a complete duplicate of an object. If b is a vector with a million values, congratulations: you now have two vectors with a million values. And, as soon as you have them, one of them gets destroyed (in the process of swapping). A lot of work, all for nothing. Move semantics avoid this needless overhead in situations that boil down to moving stuff around, in the end. Instead of creating a copy of an object it is "moved" directly from point A to point B, of sorts.
73,159,641
73,159,954
How to get a value of the return only?
How to get the value that is returned from a function without running the function again? For example: int difficulty() { char x; while (true) { if (kbhit()) { x = getch(); if (x == '1' || x == '2' || x == '3') { return x; break; } } } cout << "done"; } This function is called in: void Move(){ if (HeadY >= Height-1 || HeadY <= 0 || HeadX >= Widht-1 || HeadX <= 0) Lose = false; char level=diffculty(); //********** if(level=='2' || level=='3'){ for(int i=0;i<Ta_N;i++) if(HeadX==Ta_X[i] && HeadY==Ta_Y[i]) Lose = false; } } And called in the menu function: void menu(){ if(kbhit()){ x=getch(); if(x=='s' || x=='S'){ system("cls"); table(); while(Lose){ Line(); Input(); Move(); //*********** Sleep(50); } system("pause"); } } I need the x value only to compare it, but it runs the code again??
I am assuming you want to create x in menu() and then store it as a variable to pass down the chain of function calls started in menu(). Under this assumption what you ought to do is simple. menu() becomes: void menu(){ if(kbhit()){ char x=getch(); // CHANGED if(x=='s' || x=='S'){ system("cls"); table(); while(Lose){ Line(); Input(); Move(x); //CHANGED Sleep(50); } system("pause"); } } } Then Move() should be modified into Move(char x): void Move(char x){ // CHANGED if (HeadY >= Height-1 || HeadY <= 0 || HeadX >= Widht-1 || HeadX <= 0) Lose = false; char level = difficulty(x); // CHANGED if (level=='2' || level=='3'){ for (int i=0;i<Ta_N;i++) if (HeadX==Ta_X[i] && HeadY==Ta_Y[i]) Lose = false; } } difficulty() becomes difficulty(char x) char difficulty(char x) { //CHANGED // DELETED LINE char x; // REDUNDANT AS EXPLAINED IN COMMENT BELOW while (true) { // REDUNDANT if (kbhit()) { // DELETED LINE x = getch(); if (x == '1' || x == '2' || x == '3') { return x; // DELETE THIS break; } else throw("what happens when x != 1 or 2 or 3?"); //ADDED // REDUNDANT } else // REDUNDANT throw("what happens when kbhit() is false?"); // REDUNDANT } cout << "done"; }
73,159,681
73,189,274
What will be preferred way to share data between game engine and plugin?
I'm a beginner programmer ( I know scripting and basic C++). I'm using UnrealEngine5/C++ and want to update some variables inside engine using my own programs (Lisp) at runtime. Currently I'm using text file as a buffer. Are there better ways? I don't want each part of engine have a plug for constantly checking this file for updated values. I want general loop of engine remain intact. I don't know if you should allocate same memory addresses for variables in different programs as a solution - would like to know about established ways of doing it before inventing the wheel. I understand that answer can be complex but if you can at least guide me in terms of books and concepts that I need to understand in order to make such setup that I won't need a buffer file.
There are quite a few ways to do what you want, and they are mostly not specific to Lisp. So, I'd like to give you some general advice and add a few Lisp-related comments where appropriate. Basically, there are two extremes among the different approaches you might decide to take: Tight coupling Louse coupling Tight coupling is usually preferred when you want to remain primarily in the realm of your base language, and when maximum efficiency of the program execution is the primary goal. With tight coupling, you may use such tools as shared libraries and foreign-function interface, i.e. you'll embed the scripting language into your base runtime. With C/C++ as a base and Lisp as an embedded language, you may take a look at ECL and CLASP implementations which target this use case specifically. Tight coupling, however, is usually somewhat limiting to the embedded language, it gives you less flexibility. If your priority and main development effort will be in it (or, at least, in both platforms more or less on par), loose coupling may be more attractive. With it, you will run two (or more) separate processes and use IPC to share data and/or commands between them. There are many approaches to IPC. Using a file to share data is one of them, albeit one of the most primitive ones. A more advanced approach that might be convenient for your use case is using Unix domain sockets (as the most efficient) or the other types of sockets (plain network sockets or even websockets). Regardless of a particular mechanism selected, the basic principle is that your data should be marshaled between two separate environments, which introduces overhead. Yet, it also may help you structure the program much better. As for marshaling, once again there's a variety of approaches that also range from a more-coupled one (represented by using platform-specific binary encodings, such as Python pickle format) to less-coupled (using standard text-based data-interchange formats such as JSON). I'd say that, in general, for interfacing between such conceptually different platforms as C and Lisp, the loose coupling approach is the default as it doesn't force the paradigms and conventions of each of these environments onto each other. However, if what you have to achieve is a limited one-off task, it might be much less effort to integrate Lisp into C.
73,159,720
73,159,764
cout macro value doesn't work as expected
#include<iostream> using namespace std; #define C 1<<(8*1) int main(){ if(C==256){ int a=C; cout<<a; } } My expectation is 256 but it print 18. What's wrong with it? Thanks!
I assume your question is about std::cout << C;, not about std::cout << a;. Macros are simple copy-and-paste text replacement. When preprocessor encounters macro name, it replaces it with the definition as text without any analysis. So, what happens is that std::cout << C; is replaced with std::cout << 1<<(8*1); which should indeed print 18. That's one very good reason to not use macros. Instead, use a constant (or constexpr) variable: constexpr int C = 1 << (8 * 1); This is type safe and will never surprise you when used in any context. If you really have to use macro for some reason, make sure to wrap it in extra parantheses: #define C (1 << (8 * 1)) // but seriously, don't use macros
73,159,830
73,159,878
Why can a C++ function type alias be used to pass a lambda to a function?
Have a look at the code example listed below, I tested it with Compiler explorer (using gcc and clang) and it works and prints out the (expected) output of 200. What I am trying to figure out: why exactly is this valid C++. Or is it not? Here, I'm using the using keyword to define an alias (instead of a typedef) for the function type ft, which describes functions that take an int as argument and return an int (ft is a function type, not a function pointer type!). The equivalent typedef syntax is typedef int ft(int);. Since the C++ standard says that for every typedef there is an equivalent form using the using syntax, it is clear that using ft = int(int) is a well-defined way to specify this function type. Now comes the interesting part: I use the type ft to specify the argument type of another function (print_it), and then call it, passing a lambda function. My question is: where/how does the C++ standard say that this should actually work? I think it is a wonderfully simple way to pass lambdas around. That this works is not clear to me, as a lambda is really a functor, not a function in the strict sense. So I think it is not clear that this lambda matches the type ft and therefore can be passed to print_it (if ft was defined to be std::function<int(int)> it would be clear though). The code example: #include <iostream> using ft = int(int); void print_it (ft f, int a) { std::cout << f(a) << std::endl; } int main () { auto my_lambda = [] (int a) -> int { return 2 * a; }; print_it (my_lambda, 100); return (0); }
My question is: where/how does the C++ standard say that this should actually work? This is specified in [expr.prim.lambda.closure]/7, which specifies that a lambda's closure type has a conversion function to a function pointer type matching the lambda's parameter and return types if the lambda is non-generic and doesn't have any capture. Calling through this function pointer basically behaves as if the lambda body was just a normal function to which the pointer points, which is possible because there are no captures which could give the lambda a state that a normal function can't have. This applies here and you are using the conversion operator to implicitly convert the lambda object to a function pointer when passing it to print_it. This works since the lambda's parameter and return type matches the ft type and a function type used as type of a function parameter is adjusted to a pointer-to-function type instead. (See [dcl.fct]/5 for the last part.) For generic lambdas there is a conversion function template (see the following standard paragraph). For lambdas with a capture there is no such conversion function and therefore this wouldn't work for them.
73,159,970
73,160,069
vscode - ofstream not creating a new file, .exe works normally
I cannot create or read files using vscode with fstream. Program run from .exe works normally (creates a file empty.txt). main.cpp: #include <fstream> int main() { std::ofstream file("empty.txt"); } The above program does not create a file when run with vscode. Editor: Visual Studio Code Compiler: MinGW-w64 (MSYS2) System: Windows 10 launch.json: { "configurations": [ { "name": "C/C++: g++.exe build and debug active file", "type": "cppdbg", "request": "launch", "program": "${fileDirname}\\${fileBasenameNoExtension}.exe", "args": [], "stopAtEntry": false, "cwd": "C:\\msys64\\mingw64\\bin", "environment": [], "externalConsole": false, "MIMode": "gdb", "miDebuggerPath": "C:\\msys64\\mingw64\\bin\\gdb.exe", "setupCommands": [ { "description": "Enable pretty-printing for gdb", "text": "-enable-pretty-printing", "ignoreFailures": true }, { "description": "Set Disassembly Flavor to Intel", "text": "-gdb-set disassembly-flavor intel", "ignoreFailures": true } ], "preLaunchTask": "C/C++: g++.exe build active file" } ], "version": "2.0.0" } tasks.json: { "tasks": [ { "type": "cppbuild", "label": "C/C++: g++.exe build active file", "command": "C:\\msys64\\mingw64\\bin\\g++.exe", "args": [ "-fdiagnostics-color=always", "-g", "${fileDirname}\\**.cpp", //"${fileDirname}\\**.h", //"${file}", "-o", "${fileDirname}\\${fileBasenameNoExtension}.exe" ], "options": { "cwd": "C:\\msys64\\mingw64\\bin" }, "problemMatcher": [ "$gcc" ], "group": { "kind": "build", "isDefault": true }, "detail": "Task generated by Debugger." } ], "version": "2.0.0" }
Change cwd in both launch.json and tasks.json to "cwd": "${workspaceFolder}",. See also the official how to.
73,160,006
73,160,055
clang doesn't see base class constructors pulled in via typedef
The following code #include <vector> #include <string> template<typename T> struct V : public std::vector<T> { using Impl = std::vector<T>; using typename Impl::vector; // the constructors }; int main() { std::string empty; V<std::string> meow{42UL, empty}; } Is compiled fine by GCC 8.2 (calls the size_t, string constructor). However, clang up to 14 rejects it with <source>:14:20: error: no matching constructor for initialization of 'V<std::string>' (aka 'V<basic_string<char>>') V<std::string> meow{42UL, empty}; ^ ~~~~~~~~~~~~~ <source>:5:8: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 2 were provided struct V : public std::vector<T> ^ <source>:5:8: note: candidate constructor (the implicit move constructor) not viable: requires 1 argument, but 2 were provided <source>:5:8: note: candidate constructor (the implicit default constructor) not viable: requires 0 arguments, but 2 were provided as if V had no constructors: https://godbolt.org/z/M91zb6Pjr Replacing using typename Impl::vector; with using Impl::Impl; makes clang accept the code. What is going on here?
Since the recent resolution of CWG issue 2070 it is not possible anymore to use a dependent alias to inherit the constructor in a using declaration, except if repeating the name of the alias. You must use the same identifier to name the base class as you are using to refer to the constructor (the last unqualified-id after the nested-name-specifier), for example: using std::vector<T>::vector; or making use of the lookup of the injected class name of the base class in V: using V::vector::vector; or by a special rule for using-declarators the name of the alias may also be repeated instead of using the injected class name if it is dependent: using Impl::Impl; (see https://eel.is/c++draft/basic#class.qual-1.2 and https://eel.is/c++draft/namespace.udecl#1.sentence-3) If you write using typename Impl::vector; instead it is not inheriting a constructor, but instead vector is going to be interpreted as a type named by the injected class name in vector<T>, which then is imported as the name vector into the class scope. This requirement is to avoid that the same using line will cause the constructor to be inherited sometimes and a type name to be imported other times, depending on the specialization of the template. Basically, after the resolution you know that the using declaration with a dependent nested-name-specifier is inheriting a constructor if and only if it is ending in A::A or A::A for some name A (potentially with additional template argument lists, etc.). It seems that Clang has always implemented it this way, although I think it wasn't really correct according to the standard before the resolution of the issue.
73,160,283
73,746,679
set text align to be the center of sf::text with multi lines in SFML
I have a sf::Text with multiple lines how can I set its content alignment in the center sf::Text? with just single line i can handle it with setOrigin but with multiple lines i dont know how
Depends on what your object is. I would reccomend having the multiline object be a vector of multiple sf::Text objects (each Text object is a new line). You get the right size of the box you want your multiline text to be in and then you use origin on each line to center each text in its position. You can try something like this: class MultiLine { public: vector<sf::Text> texts; int width; int heigth; int posx;//starting position of the multiline text block int posy; int heigthSpacing; sf::Font font; int widthSpacing; MultiLine(int wid, int he) : width(wid), heigth(he) { //you can manipulate the size of the box manually via contructor or dynamically via the amount of lines and spacing between. //this is example of contructor //addvalues here, move to position here. position is important for later on as setorigin sets origin of point + pos. //you can change the pos at any time later too, but the initial pos is important } void addLine(string text) { sf::Text tmp; tmp.setCharacterSize(30); tmp.setFont(font); tmp.setString(text); tmp.setPosition(posx+width,posy+texts.size()*heigthSpacing); texts.emplace_back(tmp); } void centerText() { for(auto &v : texts) { v.setOrigin(v.getGlobalBounds().width/2, v.getGlobalBounds().height/2); v.setPosition(posx+width/2,v.getPosition().y); } } };
73,160,419
73,160,437
Is the value of a variable always guaranteed to be 1 word away from the variable created outside of scope if it comes immediately after?
int main() { {int x = 532;} int xc; int x = *(&xc+1); cout << x << endl; // prints 532 } I create an int variable with a value of 532 and then it immediately goes out of scope. I then create another int variable right after so that it has an address of 1 word before x. I then assign that value of whatever was one word past xc to x and print it, and it has the value of 532. Is this guaranteed to happen? Why/why not?
No, the arrangement and padding (and even the existence) of variables on the stack is implementation-dependent, and what you have here is Undefined Behavior. The language specifies that you must not use a pointer to access the memory of any object other than the one it points to. In this case, &xc + 1 points to memory that lies outside the allocation of xc. You cannot read or write to this location and expect any kind of predictable result. Note that it is actually a valid pointer -- you are allowed to point "one-past-the-end" of an allocation, provided you never dereference that address. To explain what's actually happening in your case: your variables are being pushed onto the stack, and the stack memory extends in the direction of lower addresses. It appears your compiler didn't bother to unwind the stack after the original x went out of scope. Alternatively, multiple values of 532 might have been initialized in memory, or in a register, and the value you're reading might not be the one that was stored at x. All this said, even this program on your computer with your compiler does not guarantee this behavior. The original variable x could be optimized away by the compiler completely because it is not used. The value of xc is uninitialized. Its location (if any) on the stack is not guaranteed. Even though x had additional scope, the compiler is not required to push and pop stack locations if it doesn't want to. The compiler is not required to understand that you're aliasing x via xc because, as already mentioned such behavior is not defined.
73,160,731
73,160,799
Why do C++ standards introduce more output methods without input counterparts?
C++20 introduces <format>(and sooner C++23 introduces <print>). I like those methods, and I always try to use std::format when it's supported rather than use a series of <<. But I notice that this evolution seems to only appear in the output. Why isn't there something like <scan> for input?
std::format and std::print are already quite a big library addition in itself and I could image that the limited resources for the standard committee to consider the addition of additional features didn't allow them to consider an input equivalent at the same time. It might also be that the committee wanted to collect more experience with std::format/std::print first before adding an input equivalent or that there are objections to such an addition in principle, in the proposed implementation details or the priority of such an addition. I couldn't find any definitive statements pointing towards any of these directions and I have no insider knowledge. Anyway, the committee is still considering a std::scan proposal as follow-up to the std::format proposal, see https://github.com/cplusplus/papers/issues/493 for a log of the procedure the proposal has gone through so far. You can also see there polls on design directions, etc. There seems to not have been much activity since 2019, but I am not sure whether this really means anything or not. In a reddit thread here from March 2022, Elias Kosunen, one of the authors of the proposal and author of scnlib mentions that there are still some unsure design questions that need to be made sure of before going forward with the proposal, hoping to be able to target C++26, but acknowledging that a farther delay would be preferable to adding a "half-baked" design to the standard.
73,160,854
73,161,163
Casting parameter-less generic lambda to a function pointer
I'm trying to cast a parameter-less generic lambda to a function pointer. This problem generally applies to generic lambdas, which parameters don't depend on the template argument. Example tries to cast the lambda with one parameter (int) which is typewise independent of the template parameter T. #include <iostream> int main() { auto lambda = []<class T>(int v) -> void { std::cout << typeid(T).name() << ' ' << static_cast<T>(v) << '\n'; }; // How do I cast lambda to a function pointer that uses operator(int)<char> // This doesn't compile, I've reached this conclusion after examining this page https://en.cppreference.com/w/cpp/language/lambda auto seeked_ptr_char = lambda.operator fptr_t<char>(); // Hacky solution :( auto mptr_char = &decltype(lambda)::operator()<char>; decltype(mptr_char) mptr_float = &decltype(lambda)::operator()<float>; (lambda.*mptr_char)(48); (lambda.*mptr_float)(52); // This is okay (tho parameter is dependent on a template argument, which is not what we are looking for) auto another_lambda = []<class T>(T v) -> void { std::cout << v << '\n'; }; void(*ptr_char)(char) = another_lambda; ptr_char(50); return 0; } Doesn't compile with x86-64 gcc 12.1 with -std=c++20 -O3 x86-64 clang 14.0.0 -std=c++20 -O3 https://godbolt.org/z/cavbT5jM3
How do I cast lambda to a function pointer that uses operator(int)<char> TL;DR: you don't. First, function pointers point to functions. Templates are not functions yet; a function template only becomes a function when you supply it with template parameters. A function pointer can point to a specific instantiation of a function template. But it cannot point to a function template. The conversion from a generic lambda to a function pointer relies on invoking a template conversion functions. As such, the lambda effectively has a conversion function like this: using func = void(int); template<typename T> operator func*(); However, that's a template conversion function. And since the type being converted to does not supply the template parameter, in order to call that function, you must explicitly provide that type. Which means you have to explicitly call the conversion function. But given the code you wrote, you worked all of that out. Which means your real problem is: How do I explicitly invoke a template conversion function if the result of the conversion is in no way related to the template parameter(s)? Lambdas don't matter here. This is all about calling a special kind of template conversion function. And the answer is... apparently, you don't. You can explicitly invoke a conversion function to the type type_name via object_name.operator type_name() syntax. The problem is this line in the standard: The conversion-type-id in a conversion-function-id is the longest sequence of tokens that could possibly form a conversion-type-id. The problem is how lambda.operator fptr_t<char>() gets parsed. See, fptr_t could be the name of a template class. And therefore, fptr_t<char> could be the name of a specialization of that class template. Therefore fptr_t<char> is "the longest sequence of tokens that could possibly form a conversion-type-id". In short, the compiler thinks you're trying to invoke the conversion function to the type fptr_t<char>. It does not matter that fptr_t is not a template, and the compiler can look around and figure that out. Parsing happens before any of that kind of thinking. So the parsing rules take priority. The entire fptr_t<char> text is taken as the typename for the conversion function. This all means that, unless the template parameter(s) for a conversion function can be deduced from the type being converted to alone, it appears that it is impossible to call such a conversion function. Such a conversion function can exist; you can declare such functions just fine. But C++ lacks any syntax for actually interacting with it. Yet another reason why lambdas with template parameters that cannot be deduced from the function arguments are not especially useful.
73,161,183
73,162,895
Use variables with both cores and tasks ESP32
Im trying to read data from an i2c device, which is recieved by core 0, then that data is stored into some global values, and then those values are readed by the core 1, and then printed out. The problem is whenever the core 0 tries to access those variables, it outputs "guru meditation error core 0 panic'ed (loadprohibited). exception was unhandled". What is the way in which the 2 cores can communicate to one another? TaskHandle_t Task1; TaskHandle_t Task2; #include <Adafruit_ADS1X15.h> Adafruit_ADS1015 ads; volatile int16_t adc0, adc1, adc2, adc3; volatile float volts0, volts1, volts2, volts3; void setup() { Serial.begin(115200); delay(1000); Serial.println("Hello!"); Serial.println("Getting single-ended readings from AIN0..3"); Serial.println("ADC Range: +/- 6.144V (1 bit = 3mV/ADS1015, 0.1875mV/ADS1115"); //create a task that will be executed in the Task1code() function, with priority 1 and executed on core 0 xTaskCreatePinnedToCore( Task1code, /* Task function. */ "Task1", /* name of task. */ 10000, /* Stack size of task */ NULL, /* parameter of the task */ 1, /* priority of the task */ &Task1, /* Task handle to keep track of created task */ 0); /* pin task to core 0 */ delay(500); //create a task that will be executed in the Task2code() function, with priority 1 and executed on core 1 xTaskCreatePinnedToCore( Task2code, /* Task function. */ "Task2", /* name of task. */ 10000, /* Stack size of task */ NULL, /* parameter of the task */ 2, /* priority of the task */ &Task2, /* Task handle to keep track of created task */ 1); /* pin task to core 1 */ delay(500); if (!ads.begin()) { Serial.println("Failed to initialize ADS."); while (1); } } void Task1code( void * pvParameters ){ for(;;){ Serial.print("Task1 running on core "); Serial.println(xPortGetCoreID()); adc0 = ads.readADC_SingleEnded(0); adc1 = ads.readADC_SingleEnded(1); adc2 = ads.readADC_SingleEnded(2); adc3 = ads.readADC_SingleEnded(3); volts0 = ads.computeVolts(adc0); volts1 = ads.computeVolts(adc1); volts2 = ads.computeVolts(adc2); volts3 = ads.computeVolts(adc3); delay(100); } } void Task2code( void * pvParameters ){ delay(500); Serial.print("Task2 running on core "); Serial.println(xPortGetCoreID()); for(;;){}{ Serial.println("-----------------------------------------------------------"); Serial.print("AIN0: "); Serial.print(adc0); Serial.print(" "); Serial.print(volts0); Serial.println("V"); Serial.print("AIN1: "); Serial.print(adc1); Serial.print(" "); Serial.print(volts1); Serial.println("V"); Serial.print("AIN2: "); Serial.print(adc2); Serial.print(" "); Serial.print(volts2); Serial.println("V"); Serial.print("AIN3: "); Serial.print(adc3); Serial.print(" "); Serial.print(volts3); Serial.println("V"); delay(100); } } void loop() { }
You can create a semaphore and take it when try to access the variable. If you done accessing it, you can give it back. When you take a semaphore, other code blocks will wait for the other to give it back. You can configure the time it should wait for a given semaphore. Here is a (link) explaining in more details. Here is an example: SemaphoreHandle_t i2cSemaphore; void createSemaphore(){ i2cSemaphore = xSemaphoreCreateMutex(); xSemaphoreGive( ( i2cSemaphore) ); } // Lock the variable indefinietly. ( wait for it to be accessible ) void lockVariable(){ xSemaphoreTake(i2cSemaphore, portMAX_DELAY); } // give back the semaphore. void unlockVariable(){ xSemaphoreGive(i2cSemaphore); } TaskHandle_t Task1; TaskHandle_t Task2; #include <Adafruit_ADS1X15.h> Adafruit_ADS1015 ads; volatile int16_t adc0, adc1, adc2, adc3; volatile float volts0, volts1, volts2, volts3; void setup() { Serial.begin(115200); delay(1000); Serial.println("Hello!"); Serial.println("Getting single-ended readings from AIN0..3"); Serial.println("ADC Range: +/- 6.144V (1 bit = 3mV/ADS1015, 0.1875mV/ADS1115"); createSemaphore(); //create a task that will be executed in the Task1code() function, with priority 1 and executed on core 0 xTaskCreatePinnedToCore( Task1code, /* Task function. */ "Task1", /* name of task. */ 10000, /* Stack size of task */ NULL, /* parameter of the task */ 1, /* priority of the task */ &Task1, /* Task handle to keep track of created task */ 0); /* pin task to core 0 */ delay(500); //create a task that will be executed in the Task2code() function, with priority 1 and executed on core 1 xTaskCreatePinnedToCore( Task2code, /* Task function. */ "Task2", /* name of task. */ 10000, /* Stack size of task */ NULL, /* parameter of the task */ 2, /* priority of the task */ &Task2, /* Task handle to keep track of created task */ 1); /* pin task to core 1 */ delay(500); if (!ads.begin()) { Serial.println("Failed to initialize ADS."); while (1); } } void Task1code( void * pvParameters ){ for(;;){ lockVariable(); Serial.print("Task1 running on core "); Serial.println(xPortGetCoreID()); adc0 = ads.readADC_SingleEnded(0); adc1 = ads.readADC_SingleEnded(1); adc2 = ads.readADC_SingleEnded(2); adc3 = ads.readADC_SingleEnded(3); volts0 = ads.computeVolts(adc0); volts1 = ads.computeVolts(adc1); volts2 = ads.computeVolts(adc2); volts3 = ads.computeVolts(adc3); unlockVariable(); vTaskDelay(100); } } void Task2code( void * pvParameters ){ delay(500); Serial.print("Task2 running on core "); Serial.println(xPortGetCoreID()); for(;;){}{ lockVariable(); Serial.println("-----------------------------------------------------------"); Serial.print("AIN0: "); Serial.print(adc0); Serial.print(" "); Serial.print(volts0); Serial.println("V"); Serial.print("AIN1: "); Serial.print(adc1); Serial.print(" "); Serial.print(volts1); Serial.println("V"); Serial.print("AIN2: "); Serial.print(adc2); Serial.print(" "); Serial.print(volts2); Serial.println("V"); Serial.print("AIN3: "); Serial.print(adc3); Serial.print(" "); Serial.print(volts3); Serial.println("V"); unlockVariable(); vTaskDelay(100); } } void loop() { }
73,161,277
73,161,860
How to wrapper ofstream?
I'm trying to wrapper the standard ofstream, and hope I can do additional compare and output. Everything goes well, except the std::endl or end used as first output token. But, when I turn on the #if0 ... #endif block in the main function, the g++ report many errors. How can I solve it? Is there a alternative solution. compile command is: g++ test.cpp -std=c++11 -ggdb -o a.out below is the code #include <fstream> #include <iostream> #include <string> using namespace std; class Logger { private: template <typename T> friend ofstream& operator<<(Logger&, T); ofstream os_; std::string file_name; uint32_t count = 0; public: // Logger(std::string name) : file_name(name), curIndentLevel_(0) explicit Logger(const std::string& name) : file_name(name) { // open the file and ready to write. os_.open(file_name, std::ofstream::out | std::ofstream::app); } }; template <typename T> inline ofstream& operator<<(Logger& log, T op) { // write stream to the target file. if ((log.count % 100) == 0) { // output a split token log.os_ << "=============" << std::endl; } log.os_ << ' '; log.os_ << op; log.os_.flush(); log.count++; return log.os_; } class MyClass { public: uint32_t value = 0xf; uint32_t x = 0; std::string file_name = "456.txt"; Logger log = Logger("456.txt"); public: MyClass() {} ~MyClass() {} }; int main() { Logger log("123.txt"); for (uint32_t i = 0; i < 5000; i++) { log << "Hello World!" << std::hex << " 0x= " << 100 << ", sdfdsfs" << " ABC " << std::dec << " =0x " << 100 << std::endl << endl; } #if 0 // why did the "end" can not be the first element? // how to solve it. log <<endl; //errors. log <<std::endl; //errors log <<std::endl<< "***** The log execute successfully."<<std::endl<<std::endl; //errors #endif log << std::dec; log << std::hex; log << "Hello World!" << std::endl; return 0; }
Just use inheritance directly. #include <iostream> #include <string> #include <fstream> using namespace std; class Logger : public ofstream { template<typename T> friend Logger& operator<<(Logger&, T); public: Logger(const string& file_name) { open(file_name); } private: uint32_t count = 0; }; template<typename T> inline Logger& operator<<(Logger& log, T op) { //write stream to the target file. auto& base_log = static_cast<ofstream&>(log); if( (log.count%100) == 0){ //output a split token base_log << "============="<<std::endl; } base_log << ' '; base_log << op; base_log.flush(); log.count++; return log; } int main() { Logger log("123.txt"); for(uint32_t i =0;i<5000;i++){ log << "Hello World!" <<std::hex<<" 0x= "<<100 <<", sdfdsfs" << " ABC "<<std::dec << " =0x " << 100<<std::endl<<endl; } log <<endl; log <<std::dec; log <<std::hex; log << "Hello World!" << std::endl; return 0; }
73,161,558
73,162,237
C++ inject member variable only if template arguments are present
I'm writing a simple generic Graph class, referencing the Boost.Graph implementation. The implementation is like this: template <typename GraphTraits, typename... Properties> class Graph { public: using vertex_type = GraphTraits::vertex_type; using vertex_iterator = GraphTraits::vertex_iterator; using edge_type = GraphTraits::edge_type; using edge_iterator = GraphTraits::edge_iterator; using container_type = GraphTraits::container_type; private: container_type container_; public: // ... details ... }; struct DefaultGraphTraits { using vertex_type = std::ptrdiff_t; using vertex_iterator = std::vector<vertex_type>::iterator; using edge_type = std::pair<vertex_type, vertex_type>; using edge_iterator = std::list<vertex_type>::iterator; using container_type = std::vector<std::list<vertex_type>>; }; struct DirectedGraphTraits { using vertex_type = std::ptrdiff_t; using vertex_iterator = std::vector<vertex_type>::iterator; using edge_type = std::pair<vertex_type, vertex_type>; using edge_iterator = std::list<vertex_type>::iterator; static constexpr bool directed_ = true; using container_type = std::vector<std::list<vertex_type>>; }; using GraphDefault = Graph<DefaultGraphTraits>; using DiGraph = Graph<DirectedGraphTraits>; What I want is to "inject" properties (such as edge weight, vertex color, etc), possibly multiple properties, only if necessary. Boost.Graph is like this: typedef adjacency_list< listS, vecS, directedS, no_property, property< edge_weight_t, int > > graph_t; As of 2000, Boost.Graph was incredibly well-made, but I don't like several things in 2022's perspective: Just instantiating a graph needs five template parameters and we have to set no_property even if we don't need to set properties at all It seems to be able to set only one property for vertex and one property for edge. What if I want to have edge color, edge weight, and edge flow at the same time? So I want to know how to conditionally "inject" member variables when additional template arguments Properties are at present What I want is like this: template <typename T> struct EdgeWeightProperty { using property_type = T; }; struct EdgeColorProperty { using property_type = int; }; using MyGraph = Graph<DefaultGraphTraits, EdgeWeightProperty<float>, EdgeColorProperty>; I want MyGraph automatically generates member variables something like std::unordered_map<edge_type, EdgeWeightProperty<float>::property_type> and std::unordered_map<edge_type, EdgeColorProperty::property_type> at compile-time. What modern C++ design pattern should I use?
You could store the maps in a tuple. If you don't mind changing from unordered_map to map, it could be done like this: template <typename GraphTraits, typename... Properties> class Graph { public: using vertex_type = GraphTraits::vertex_type; using vertex_iterator = GraphTraits::vertex_iterator; using edge_type = GraphTraits::edge_type; using edge_iterator = GraphTraits::edge_iterator; using container_type = GraphTraits::container_type; static constexpr size_t property_count() { return sizeof...(Properties); } // get property map by `get<index>()`: template<size_t I> auto& get() { return std::get<I>(properties_); } template<size_t I> const auto& get() const { return std::get<I>(properties_); } private: container_type container_; std::tuple< std::map<edge_type, typename Properties::property_type>... > properties_; public: // ... details ... }; Demo If they must be unordered_maps, you need to write hashers for all your edge_types. Using std::pair<A, B> as a Key in a map works out of the box though since operator< is defined for types where A and B also have operator< defined.
73,161,739
73,162,016
Rotate a 2-D array by 90 degrees
How can I take the array size input from the user and pass it to the function. I tried #define inside the function, it doesn't work since the array definition needs the array bound at compile time. I tried global variable too, it says to define a integer constant which is not feasible in my case since I want to get the size from the user. How can I solve this issue? #include <iostream> using namespace std; // reverse the transposed matrix as step 2 void reverseColumns(int arr[N][N]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N / 2; j++) { int temp = arr[i][j]; arr[i][j] = arr[i][N - j - 1]; arr[i][N - j - 1] = temp; } } } // take the transpose of matrix as step 1 void transposeMatrix(int arr[N][N]) { for (int i = 0; i < N; i++) { for (int j = i; j < N; j++) { int temp = arr[i][j]; arr[i][j] = arr[j][i]; arr[j][i] = temp; } } } void rotateMatrix(int mat[N][N]) { transposeMatrix(mat); reverseColumns(mat); } // printing the final result void displayMatrix(int mat[N][N]) { int i, j; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) cout << mat[i][j] << "\t"; cout << "\n"; } cout << "\n"; } int main() { int T, N; cin >> T; while (T > 0) { cin >> N; int mat[N][N]; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cin >> mat[i][j]; } } int res[N][N]; rotateMatrix(mat); displayMatrix(mat); } return 0; }
One way to make it work is get the input of rows and cols from user and make a one dimensional array dynamically. for example: Let ROWS and COLS be the values you got via cin. Then the array can be declared as int* arr = new int[ROWS * COLS]; Instead of writing arr[i][j] you have to write arr[i * COLS + j] Also you have to delete the array using delete[] arr;
73,162,229
73,162,271
Basic C++ problem - Using variable within the class
I have problem with C++ class. Is there have any way to reuse variable in the same class in the header file? I have try PubSubClient mqttClient(this->secureClient); PubSubClient mqttClient(mqtt.secureClient); but fail. Why? #ifndef __MQTT_H_ #define __MQTT_H_ #include "Arduino.h" #include "WiFi.h" #include "WiFiClientSecure.h" #include "PubSubClient.h" class MQTT { public: bool initWiFi(); String macAddress6btye(void); void callback(char *topic, byte *payload, unsigned int length); bool mqttConnect(); bool mqttPublish(const String &endPoint, const String &payload); int getStrength(uint8_t points); private: WiFiClientSecure secureClient; PubSubClient mqttClient(this->secureClient); }; #endif
The declaration PubSubClient mqttClient(this->secureClient); is treated as a function declaration. An invalid one. If you want to initialize the member variable (using other member variables), you need to do it with a constructor initializer list: class MQTT { public: MQTT() : secureClient(), mqttClient(secureClient) // Initialization here { // Empty function body } // ... WiFiClientSecure secureClient; PubSubClient mqttClient; // No initialization here };
73,162,238
73,162,508
Is there any chance that CLOCK_REALTIME changes time automatically?
I'm using linux api clock_gettime(realtime) to print current time. Check log index ending with 649 and 917. The real clock time was 1646948676.999081502(at index 649) ,but after 10 secs it suddenly jumped more than >24 hours back and was 1646860487.614595043(index 917). Main thing i wanna know is what is VuC offset? Will VucOffset affect this realtime? and Could you please explain what is the reason for time jump? and how can we avoid this? 221649 2022/03/10 02:44:37.000000 PF_CLOCK_SYNC CLOCK_MONOTONIC_RAW=35.228995663 s CLOCK_MONOTONIC=35.228996808 s CLOCK_REALTIME=1646948676.999081502 s 230583 2022/03/10 02:44:46.000000 receiveTMPData data received !! 230584 2022/03/10 02:44:46.000000 TMP::Data received is: -56563019 230585 2022/03/10 02:44:46.000000 TMP:TM_OUTPUT_VUC_OFFSET IS SET!! 231917 2022/03/10 02:44:47.000000 PF_CLOCK_SYNC CLOCK_MONOTONIC_RAW=45.230177586 s CLOCK_MONOTONIC=45.230296214 s CLOCK_REALTIME=1646860487.614595043 s
CLOCK_REALTIME is your classic "wall clock", similar in spirit to what is returned by the older gettimeofday() function call. In particular, it is non-monotonic, which means that it can be expected under some circumstances to 'jump' forward or backwards by an arbitrary amount. Generally "some circumstances" will be limited to "immediately after the local user calls settimeofday() or by some other mechanism changes his computer's clock setting"; but it is also possible for an automated clock-synchronization (like ntpd or ptpd) to automatically adjust the clock forwards or backwards if it feels the need to do so. (I wouldn't expect either of those to adjust the clock by 24 hours unless they decided that the computer's existing clock-value was 24 hours off from the clock they are trying to synchronize it to, of course).
73,162,806
74,124,118
ListView with List Items arranged on Half Circle using QML
I'm Trying to make a Circular ListView with List Items arranged on Half Circle. it should look something like this: I'm using Qt open source license and i cannot find a controller similar in QtControls. Please any idea or suggestion ? Thanks in advance
Here is a solution based on the link that folibis shared in the comments above using PathView to layout the items of a model along a PathArc. import QtQuick import QtQuick.Window import QtQuick.Shapes Window { visible: true width: 400 height: 400 Shape { ShapePath { strokeWidth: 2 strokeColor: "black" fillColor: "lightgrey" startX: 0 startY: 0 PathArc { x: 0 y: 400 radiusX: 400 radiusY: 400 } } } Shape { x: 100 ShapePath { strokeWidth: 2 strokeColor: "grey" startX: 0 startY: 0 PathArc { x: 0 y: 400 radiusX: 400 radiusY: 400 } } } PathView { x: 100 model: ["Apple", "Banana", "Cherry", "Dragonfruit", "Grapefruit", "Orange", "Papaya"] delegate: Item { width: 50 height: 50 Rectangle { height: 50 width: 260 radius: 25 color: "lightgrey" } Rectangle { id: circle width: 50 height: 50 radius: 25 color: "darkgrey" } Text { anchors.leftMargin: 10 anchors.left: circle.right anchors.verticalCenter: parent.verticalCenter text: modelData font.pixelSize: 24 } } path: Path { // Those 2 coordinates are a bit of hack to push down the first item on the actual arc // so it won't stick out the top. There might be a better way of doing that startX: 18 startY: 35 PathArc { x: 0 y: 400 radiusX: 400 radiusY: 400 } } } }
73,162,859
73,163,323
Qt C++ unable to connect to QTcpServer using Telnet
I have watched VoidRealm's Youtube video, C++ Qt 67 - QTCPServer - a basic TCP server application and followed his instructions, however, I can't connect to the QTcpServer I created using Telnet. My Code: //myserver.h #ifndef MYSERVER_H #define MYSERVER_H #include <QObject> #include <QDebug> #include <QTcpServer> #include <QTcpSocket> class MyServer : public QObject { Q_OBJECT public: explicit MyServer(QObject *parent = nullptr); void newConnection(); signals: private: QTcpServer *server; }; #endif // MYSERVER_H //myserver.cpp #include "myserver.h" MyServer::MyServer(QObject *parent) : QObject{parent} { server = new QTcpServer(this); connect(server,SIGNAL(newConnection()),this,SLOT(newConnection())); if(!server->listen(QHostAddress::Any, 1234)) { qDebug() << "Server could not start!"; }else{ qDebug() << "Server started!"; } } void MyServer::newConnection() { QTcpSocket *socket = server->nextPendingConnection(); socket->write("hello client\r\n"); socket->flush(); socket->waitForBytesWritten(3000); socket->close(); } Running this code, in the Console screen I get qt.core.qobject.connect: QObject::connect: No such slot MyServer::newConnection() in ..\First_Server\myserver.cpp:8 Server started! but when I open a command prompt and do the following steps: ...>telnet Welcome to Microsoft Telnet Client Escape Character is 'CTRL+]' Microsoft Telnet> open 127.0.0.1 1234 Connecting To 127.0.0.1... It is not connecting. Can anyone tell me what I have done wrong? I am using Qt 6.3.0.
You error message indicates the issue: qt.core.qobject.connect: QObject::connect: No such slot MyServer::newConnection() in ..\First_Server\myserver.cpp:8 Server started! You have created the connection between the signal and slot here. connect(server,SIGNAL(newConnection()),this,SLOT(newConnection())); First of all, it is not a good idea to have the same slot name as the signal as it becomes confusing. I would call your slot as "handleNewConnection" for example. Secondly, you ought to use the "new" signal-slot syntax. Thirdly, and most importantly, you have not declared your newConnection() method to be a slot. You would need to declare it so in your header file: private Q_SLOTS: void newConnection(); You can also make the slots public if it has to be accessed from outside, it looks like that you would only use it privately here.
73,163,384
73,163,646
Syntax for check if all variadic parameters are trivially copyable
Yesterday I answered this question. One user commented that it will work only for trivally copyable data. That is clear, but not enforced. I wanted to add a static_assert, but I use the wrong syntax. Here I need help. To explain a little bit more. The functions can take containers that have a size() and data() member function, like for example a std::vector and then copies the underlying data for all containers. It cries for C++20 concepts. But I would like to see at first a C++17 solution. The problem is in line static_assert(std::conjunction_v<std::is_trivially_copyable_v<std::remove_pointer<decltype(std::declval<std::remove_cvref_t<args>().data())>::type>...>, "Not trivially copyable"); Instead of std::conjunction a fold expression could be used as well. What is the correct syntax? Code: #include <iostream> #include <vector> #include <array> #include <numeric> #include <cstddef> #include <memory> #include <algorithm> #include <utility> #include <type_traits> template<typename...Args> std::pair<void*, size_t> copyData(Args...args) { //static_assert(std::conjunction_v<std::is_trivially_copyable_v<std::remove_pointer<decltype(std::declval<std::remove_cvref_t<args>().data())>::type>...>, "Not trivially copyable"); size_t overallSize = (0 + ... + (args.size() * sizeof(std::remove_cvref_t<decltype(args)>::value_type))); std::byte* destination = new std::byte[overallSize]; std::byte* destinationAddress = destination; ((destinationAddress = std::copy((std::byte*)args.data(), (std::byte*)args.data() + (args.size() * sizeof(std::remove_cvref_t<decltype(args)>::value_type)), destinationAddress)), ...); return { destination, overallSize }; } int main() { // Some demo data with different data types std::vector <unsigned char> uc{ 0,1,2,3,4 }; std::array <short, 3> ss{ 5,6,7 }; std::vector <unsigned int> ui{ 8,9,10,11,12,13,14,15 }; std::array <long, 2> sl{ 16,17 }; std::vector <unsigned long long> ull{ 18,19,20,21,22,23 }; // Call function with any number of arguments const auto& [pointer, size] = copyData(uc, ss, ui, sl, ull); // Some debug output for (size_t i{}; i < size; ++i) std::cout << ((int)((std::byte*)(pointer))[i]) << ' '; delete[] pointer; } Bonus would be to enforce that the parameter types have a size() and data() function and a value_type But not that important, because, if they have not, then the compilation will fail anyway. Which is OK.
The correct syntax would be static_assert(std::conjunction_v< std::is_trivially_copyable< std::remove_pointer_t< decltype(std::declval<Args&>().data())>>...>, "Not trivially copyable"); However, there is no need to use decltype(std::declval<Args&>().data()) to get the return type of the data(), since you are already inside the function, a simple decltype(args.data()) should be enough. static_assert(( std::is_trivially_copyable_v< std::remove_pointer_t<decltype(args.data())>> && ...), "Not trivially copyable");
73,163,428
73,186,571
Alpha-beta pruning with a silly move
After learning about alpha-beta pruning algorithm for a while, I decided to write a simple chess program. However, when running the program, the computer decides to make a silly move. I don't know where the functions are written wrong. What do I have to fix for the program to work properly. This is my static evaluation function, where m_turn is the side in turn, and m_xturn is the side that has not yet turned.: int CChess::Evaluate() { int score = 0; for (int r = 0; r < CHEIGHT; r++) for (int c = 0; c < CWIDTH; c++) if (m_color[r][c] == m_turn) score += PIECE_VALUE[m_piece[r][c]]; else if (m_color[r][c] == m_xturn) score -= PIECE_VALUE[m_piece[r][c]]; return score; } Alpha-beta pruning function: int CChess::AlphaBeta(int depth, int alpha, int beta, bool isMaxPlayer) { if (depth == 0) return Evaluate(); std::vector<CChessMove> move_list = GenMove(); size_t n = move_list.size(); if (isMaxPlayer) { for (size_t i = 0; i < n; i++) { CChessPiece piece = Move(move_list[i]); int value = AlphaBeta(depth - 1, alpha, beta, false); UnMove(move_list[i], piece); if (value > alpha) alpha = value; if (alpha >= beta) break; } return alpha; } for (size_t i = 0; i < n; i++) { CChessPiece piece = Move(move_list[i]); int value = AlphaBeta(depth - 1, alpha, beta, true); UnMove(move_list[i], piece); if (value < beta) beta = value; if (alpha >= beta) break; } return beta; } The function to find the best move. CChessMove CChess::ComputerThinks() { int best_value = -CCHESS_INFINITY; CChessMove best_move = { {-1, -1}, {-1, -1 } }; std::vector<CChessMove> move_list = GenMove(); size_t n = move_list.size(); for (size_t i = 0; i < n; i++) { CChessPiece piece = Move(move_list[i]); int value = AlphaBeta(CCHESS_DEPTH, -CCHESS_INFINITY, CCHESS_INFINITY, false); UnMove(move_list[i], piece); if (value > best_value) { best_value = value; best_move = move_list[i]; } } return best_move; }
What this really means is that your engine thought it found a refutation. For example, perhaps it analyzed QxP at depth 1. It would think that it had just won a pawn, which is great! But, one move later it realizes that it would lose the queen. This is a problem even at higher depths - an engine might thing QxP leads to a series of captures that ends with it being a pawn up, but in reality loses a rook at the very last capture that it didn't see. I would recommend implementing quiescience search as others in the comments have suggested, which plays through all captures instead of directly evaluating. Since there are very few captures compared to normal moves in a given position this is cheaper than trying to add a few extra depth. I would also highly recommend putting it in a Negamax framework rather than the standard Alpha-Beta. It's much simpler.
73,163,473
73,168,291
Best alternative to passing std::optional<std::shared_ptr<Data>> as parameter?
I have some existing code that in many places passes boost::optional<std::shared_ptr<Data>> as a parameter to a function. The function itself does not need "ownership" of the function so copying the shared pointer is both inefficient and misleading. If it wasn't for the 'optional' I would change this to take a Data const& instead and deference the shared pointer in the call. However I can't do this with optional as you can't have an optional reference. I've seen alternative of just passing a raw pointer instead of a reference as it exactly fits the semantics required. However objections are sometimes raised to using raw pointers rightly or wrongly. Is there a better way to pass this value other than just as a Data const * that ideally works in C++11 but any thoughts are required. Closing and Linking to other answers are welcome if this is a duplicate, but the other answers I've seen tend to just say that optional<T&> is wrong or to use a T* without really talking about best style or alternatives. Edit: Changed to boost::optional instead of std::optional as that is what is being used as the codebase is for the moment C++11
First, there is nothing wrong with passing a raw pointer provided: the function does not store the pointer for later use (takes/shares ownership) passing nullptr to the function is meaningful But lets look deeper into your type: boost::optional<std::shared_ptr<Data>> So this can be a shared pointer or none. And a shared pointer can also be a nullptr. So there are 3 ways to call your function: foo(boost::none); foo(boost::make_optional(std::shared_ptr()); // nullptr foo(boost::make_optional(std::make_shared(data))); Does your function really make a distinction between none and nullptr. That exists but is rather rare. If not then the optional is unnecessary. PS: Don't forget to check the std::shared_ptr before use. I really wish there would be a std::shared_ref.
73,164,072
73,189,510
Call Win32 DeviceWatcher API from Dynamic Link Library
I create a DLL project in VS 2022. How is it possible to add a call to the Win32 DeviceWatcher API? I need to add this to use it: using namespace Windows::Devices::Enumeration; using namespace Windows::Foundation But where must I add references to the Win32 API?
The DeviceWatcher Class is Windows Runtime API. I suggest you should create a Windows Runtime component DLL or class library universal windows. For more details I suggest you could refer to the Doc: DLLs
73,164,605
73,165,455
Qt C++ QTcpServer not connecting to Threaded Socket
I have worked through C++ Qt 68 - QTcpServer using multiple threads and followed his steps, but I can't seem to get the program to work correctly. I am using Qt 6.3.0 and the only difference between VoidRealm's code and mine is that I am using the new Signals and Slots system. My Code: //myserver.h #ifndef MYSERVER_H #define MYSERVER_H #include <QTcpServer> #include <QObject> #include <QDebug> #include "mythread.h" class MyServer : public QTcpServer { Q_OBJECT public: explicit MyServer(QObject *parent = nullptr); void startServer(); protected: void incomingConnection(int socketDescriptor); }; #endif // MYSERVER_H //myserver.cpp #include "myserver.h" MyServer::MyServer(QObject *parent) : QTcpServer{parent} { } void MyServer::startServer() { if(!this->listen(QHostAddress::Any, 1234)) { qDebug() << "Could not start Server!"; } else { qDebug() << "Listening..."; } } void MyServer::incomingConnection(int socketDescriptor) { qDebug() << socketDescriptor << " Connectng..."; MyThread *thread = new MyThread(socketDescriptor, this); connect(thread, &QThread::finished, thread, &QObject::deleteLater); thread->start(); } //mythread.h #ifndef MYTHREAD_H #define MYTHREAD_H #include <QThread> #include <QObject> #include <QTcpSocket> #include <QDebug> class MyThread : public QThread { Q_OBJECT public: MyThread(int ID, QObject *parent = nullptr); void run(); void readyRead(); void disconnected(); signals: void error(QTcpSocket::SocketError socketError); private: QTcpSocket *socket; int socketDescriptor; }; #endif // MYTHREAD_H //mythread.cpp #include "mythread.h" MyThread::MyThread(int ID, QObject *parent) :QThread(parent) { this->socketDescriptor = ID; } void MyThread::run() { qDebug() <<socketDescriptor << " Starting Thread"; socket = new QTcpSocket(); if(!socket->setSocketDescriptor(this->socketDescriptor)) { emit error(socket->error()); return; } connect(socket, &QIODevice::readyRead, this, &MyThread::readyRead,Qt::DirectConnection); connect(socket, &QTcpSocket::disconnected, this, &MyThread::disconnected,Qt::DirectConnection); qDebug() << socketDescriptor << " Client Connected!"; exec(); } void MyThread::readyRead() { QByteArray Data = socket->readAll(); qDebug() << socketDescriptor << " Data in: " << Data; socket->write(Data); } void MyThread::disconnected() { qDebug() << socketDescriptor << " Disconnected"; socket->deleteLater(); quit(); } When Running this, I get the console saying Listening..., but when I then use command prompt and change it to telnet using ...> telnet, and then type ...> open 127.0.0.1 1234, all I am getting is: Welcome to Microsoft Telnet Client Escape Character is 'CTRL+]' Microsoft Telnet> open 127.0.0.1 1234 Connecting To 127.0.0.1... After which nothing happens. What exactly am I doing wrong?
I found my problem. The int in the incomingConnection(int socketDescriptor) should have been a qintptr, making it incomingConnection(qintptr socketDescriptor) The program works now.
73,164,881
73,168,344
Programming principles and practice using C++ error: constexpr
In Stroustrup's "Programming principles and practice" book, there's an example of constexpr like this: void user(Point p1) { Point p2 {10,10}; Point p3 = scale(p1); // OK: p3 == {100,8}; run-time evaluation is fine constexpr Point p4 = scale(p2); // p4 == {100,8} constexpr Point p5 = scale(p1); // error: scale (p1) is not a constant // expression constexpr Point p6 = scale(p2); // p6 == {100,8} // . . . } But think he is mistaken: p2although initialized with constant expression arguments (literals here 10, 10) it is not a constexpr object because it is not declared so. So normally p4 and p6 are in error here: (cannot use p2 in a constant expression). it is like p1. To correct it: constexpr Point p2{10, 10};
You know who is really good at telling you if something is allowed as a constexpr? Your compiler. https://godbolt.org/z/4Kdocx83v And you are right, it's broken.
73,165,096
73,166,579
How to initialize constexpr static class members per class instantiation basis?
Basically, I want to allow the clients of the class Foo to define its static constexpr member variables using arbitrary values based on the template type argument they pass to it when instantiating Foo. Here is an MRE: #include <iostream> #include <concepts> template < std::unsigned_integral size_type, class Allocator = std::allocator<char> > class Foo { public: static constexpr size_type constant1 { 20 }; static constexpr size_type constant2 { 30 }; void dummy_func( ) const { std::cout << constant1 << ' ' << constant2 << '\n'; } }; int main( ) { Foo<std::uint32_t> fooInstance1; fooInstance1.dummy_func( ); // prints: 20 30 // I want these static members to be initialized // by the client but this dummy solution does not work // Foo<std::uint64_t>::constant1 { 120 }; // Foo<std::uint64_t>::constant2 { 130 }; Foo<std::uint64_t> fooInstance2; fooInstance2.dummy_func( ); // should print: 120 130 } Note that the values 20 and 30 are for demonstration purposes and don't need to be inside the class since I want to force the client to decide on their own which values they want their version of Foo to have for its constant1 and constant2. I have also taken a look at this similar question but couldn't make it work for the above specific case. One of the possible approaches that come to my mind is to use variable templates instead. But I'm not sure how. Another one is an explicit instantiation of Foo. Or maybe partial instantiation? Now I want to mention that the class should obviously be able to go in a header file and then be included in whichever source file that needs to instantiate it and use it. Is there a simple method to achieve this?
ITNOA My assumption is Foo class has many static constexpr variables and writer of Foo class does not like to write long template signature So I hope to below solution is simple and scalable enough for Foo class writer template <std::unsigned_integral size_type, size_type... args> class Foo { public: static constexpr size_type constant1{ std::get<0>(internal_values) }; static constexpr size_type constant2{ std::get<1>(internal_values) }; void dummy_func() const { std::cout << constant1 << ' ' << constant2 << std::endl; } private: static constexpr std::tuple<size_type, size_type> internal_values{ std::tuple<decltype(args)...>(std::forward<size_type>(args)...) }; }; and for use of this class you can just write simple code like below int main() { auto fooInstance1 = Foo<std::uint32_t, 20, 30>(); fooInstance1.dummy_func(); // prints: 20 30 auto fooInstance2 = Foo<std::uint64_t, 200, 300>(); fooInstance2.dummy_func(); // prints: 200 300 }
73,165,179
73,165,396
What does system_clock::now() value after seconds represent in C++ 20?
I'm exploring the timestamp in C++ 20 returned from system_clock::now() and when I print out the returned std::chrono::time_point it prints the date and time in the format YYYY-MM-DD HH:MM:SS.xxxxxxx. Any idea what the xxxxxxx value is? I assumed microseconds initially but I realised microseconds are to six decimal places whereas this value is always to seven. I'm running this in VS 2022. #include <iostream> #include <chrono> int main() { using namespace std::chrono; auto timeDate = zoned_time{ current_zone(), system_clock::now() }; std::cout << timeDate << std::endl; // Output: 2022-07-29 08:55:22.8582577 BST }
It's the fractional part of a second. The output you're getting comes from operator<<(zoned_time). This outputs the time in the format "{:L%F %T %Z}" (see cppreference.com). The %T part of the format is equivalent to "%H:%M:%S" (reference) and the %S specifies the seconds as a decimal floating-point number with a precision matching that of the precision of the input (i.e. the precision of system_clock::now() in your case).
73,165,184
73,167,705
How to rotate scene OpenGL with Qt
I've got couple of methods to get reaction on some Qt events. In one of those methods i'm drawing point in OpenGl widget. And in another I want to rotate them on some angle. The scene is plane scene. Here are those methods: #include "GLMap.h" GLMap::GLMap{} void GLMap::initializeGL(){ glClearColor(r,g,b,alpha); } void GLMap::resizeGL(int w, int h){ glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glViewport(0,0,(GLint)w,(GLint)h); glOrtho(0,1024,720,0,-1,1); glPushMatrix(); } void GLMap::paintGL(){ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if(pointsVec.size()!=0){ glPushMatrix(); foreach(QPoint pt, pointsVec){ draw(pt.x(),pt.y(),GL_POINTS); } glPopMatrix(); } } void GLMap::draw(int x, int y, GLenum type){ glPointsSize(5); glBegin(type) glColor3f(0,0,0); glVertex2i(x,y); glEnd(); } void GLMap::mouseDoubleClickEvent(QMouseEvent *event){ cutPt.setX(event->x()); curPt.setY(event->y()); pointsVec.push_back(curPt); repaint(); } void GLMap::wheelEvent(QWheelEvent *event){ anlge+=0.9; if(ang le>360.0){ angle = 0.0f; } glPopMatrix(); glLoadIdentity(); glRotatef(angle,0.0,0.0,1.0f); glPushMatrix(); } The rotation don't want to be done. What is wrong in my code.
The glRotatef() function applies a rotation to the matrix currently at the top of the matrix stack. When you draw, it does so using the matrix currently at the top. And when you glPopMatrix(), you revert the matrix stack to the one below. So the pattern while issuing commands in a painting function will typically look more like: glPushMatrix(); glRotatef( angle, vector ); drawMyStuff(); glPopMatrix(); In your case, you are not applying the rotation when you draw in your paint function. The gl code in your wheel event handler doesn't look like it belongs there. There is no drawing happening there currently, (there shouldn't be, you should call updateGL() after changing the angle so that the paint() function subsequently handles it.) and you have push/pop reversed... You want to match you push and pop commands carefully. If you are just drawing one thing, you might not need them, as they are typically used for maintaining a tree of transforms where child objects rotate with their parents. Also, you will want to make sure you are working with the right stack. You will need to use glMatrixMode( GL_PROJECTION ) and glMatrixMode( GL_MODELVIEW ) to make the transform functions work on the right stack at the right time.
73,165,250
73,165,387
no default constructor exists for class Move
I developed two modules with separate implementation and interfaces. These are the ones: This is file Move.h: #pragma once #include "utils.h" class Move { private: int x; int y; public: Move(int x_inp, int y_inp); char getX(); int getY(); }; And this is Move.cpp: #include "Move.h" Move::Move(int x_inp, int y_inp) { int size = 10 this->x = x_inp; this->y = y_inp; }; int Move::getX() { return this->x; }; int Move::getY() { return this->y; } This is the file Node.h: #pragma once #include "Move.h" #include <vector> class Node { private: Move move; Node* parent; std::vector <Node*> children; public: Node(Move inp_move, Node* parent_inp); double value(const float EXPLORE_CONST); void add_children(std::vector<Node*>); }; #include "Node.cpp" Node::Node(Move inp_move, Node* parent_inp) { // this is where compilation error rises. this->move = inp_move; this->parent = parent_inp; } void Node::add_children(std::vector<Node*> list_of_children) { for (Node* item : list_of_children) { this->children.push_back(item); } } It always gives me the error that no default constructor exists for class "Move". I am really stuck and try to figure out the solution but didn't find the answer. Can you guys help me please. Thanks
you should try literally adding a default constructor to your "Move" class. public: Move() {} //default constructor Move(int x_inp, int y_inp); char getX(); int getY(); }; ´´´´
73,165,322
73,165,920
RegEnumValueA returns 87 ("Invalid Parameter")
I am currently implementing functions and classes from Borland C++ Builder 5 in Visual Studio 2022. One of the classes is used to handle Windows registry IO, and one of its methods is supposed to return a list of values which the current key contains. I am using Windows' RegEnumValueA function which, after passing correct arguments, always returns 87 – which stands for "Invalid Parameter". The method looks as follows: void __fastcall TRegistry::GetValueNames(TStrings* Strings) { HKEY hKey = m_CurrentKey; DWORD dwIndex = 0; CHAR cValueName[TREG_MAX_VALUES_BUF_SIZE] = {}; LPSTR lpValueName = cValueName; DWORD dwValueBufSize = TREG_MAX_VALUES_BUF_SIZE; LPDWORD lpcchValueName = &dwValueBufSize; LPDWORD lpType = NULL; BYTE cData[TREG_MAX_VALUES_BUF_SIZE] = {}; LPBYTE lpData = cData; LPDWORD lpcbData = NULL; long res = RegEnumValueA(hKey, dwIndex, lpValueName, lpcchValueName, NULL, lpType, lpData, lpcbData); while (res != ERROR_NO_MORE_ITEMS) { if (res != ERROR_SUCCESS) { throw(Exception(AnsiString(res))); } else { ++dwIndex; res = RegEnumValueA(hKey, dwIndex, lpValueName, lpcchValueName, NULL, lpType, lpData, lpcbData); } } } As you can see, all the parameters are set correctly. My suspicion is that the NULL passed after lpcchValueName is causing this problem, since I've seen some people having the same issue after looking it up. Unfortunately, these were problems from years ago and were related to system-specific issues on e.g. Windows NT. The call to this method looks as follows: int main() { TRegistry* treg = new TRegistry; // Create a TRegistry object if (treg->OpenKey(AnsiString("TRegistryTest"), false)) // Open the TRegistryTest key { if (treg->OpenKey(AnsiString("subkey1"), true)) // Open the subkey1 key { TStringList ts; treg->GetValueNames(&ts); // Write the value names into a TStringList } } delete treg; } TStringList is essentially a container which stores AnsiString values, which in turn are basically glorified std::strings. I expected the RegEnumValueA function to exit with code 0 as long as there are registry values left to read - in this case, there are 4 values in total in TRegistryTest/subkey1. Changing TREG_MAX_VALUES_BUF_SIZE does not influence the result at all - it's currently set to a value of 200.
Your lpcbData parameter, which you have set to NULL is invalid. This should be the address of a DWORD that specifies the size (in bytes) of the buffer pointed to by the lpData parameter (i.e. the size of the cData array). From the documentation: [in, out, optional] lpcbData A pointer to a variable that specifies the size of the buffer pointed to by the lpData parameter, in bytes. When the function returns, the variable receives the number of bytes stored in the buffer. This parameter can be NULL only if lpData is NULL. Also, note that, on success, the values in the variables pointed to by that lpcbData argument and by lpcchValueName (i.e. dwValueBufSize) will be modified to contain the actual sizes of the data/value returned. So, you should reset those before each call. For lpcchValueName, you would use a line like dwValueBufSize = TREG_MAX_VALUES_BUF_SIZE;, with similar code for the lpcbData target, depending on what you call that variable. (And I'm not sure it's an especially good idea to use the same size variable for both, as your comment seems to suggest.)
73,165,810
73,168,951
Vulkan vertex drawing order
I am currently getting into vulkan and am now at the point where I want to draw a qube with perspective projection. But the drawing order of the faces doesnt seem to woek right. This is the depth stencil info of my pipeline const auto depth_stencil_state_create_info = VkPipelineDepthStencilStateCreateInfo{ .sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO, .pNext = nullptr, .flags = 0, .depthTestEnable = true, .depthWriteEnable = true, .depthCompareOp = VK_COMPARE_OP_LESS, .depthBoundsTestEnable = false, .stencilTestEnable = false, .front = VkStencilOpState{}, .back = VkStencilOpState{}, .minDepthBounds = 0.0f, .maxDepthBounds = 1.0f }; And the rasterization into const auto rasterization_stage_create_info = VkPipelineRasterizationStateCreateInfo { .sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO, .pNext = nullptr, .flags = 0, .depthClampEnable = false, .rasterizerDiscardEnable = false, .polygonMode = VK_POLYGON_MODE_FILL, .cullMode = VK_CULL_MODE_NONE, .frontFace = VK_FRONT_FACE_CLOCKWISE, .depthBiasEnable = false, .depthBiasConstantFactor = 0.0f, .depthBiasClamp = 0.0f, .depthBiasSlopeFactor = 0.0f, .lineWidth = 1.0f }; I am using a vertex struct with a glm::vec3 for position and color. Those are my vertices const auto vertices = std::vector<vertex>{ // left face (white) {{-.5f, -.5f, -.5f}, {.9f, .9f, .9f}}, {{-.5f, .5f, .5f}, {.9f, .9f, .9f}}, {{-.5f, -.5f, .5f}, {.9f, .9f, .9f}}, {{-.5f, .5f, -.5f}, {.9f, .9f, .9f}}, // right face (yellow) {{.5f, -.5f, -.5f}, {.8f, .8f, .1f}}, {{.5f, .5f, .5f}, {.8f, .8f, .1f}}, {{.5f, -.5f, .5f}, {.8f, .8f, .1f}}, {{.5f, .5f, -.5f}, {.8f, .8f, .1f}}, // top face (orange, remember y axis points down) {{-.5f, -.5f, -.5f}, {.9f, .6f, .1f}}, {{.5f, -.5f, .5f}, {.9f, .6f, .1f}}, {{-.5f, -.5f, .5f}, {.9f, .6f, .1f}}, {{.5f, -.5f, -.5f}, {.9f, .6f, .1f}}, // bottom face (red) {{-.5f, .5f, -.5f}, {.8f, .1f, .1f}}, {{.5f, .5f, .5f}, {.8f, .1f, .1f}}, {{-.5f, .5f, .5f}, {.8f, .1f, .1f}}, {{.5f, .5f, -.5f}, {.8f, .1f, .1f}}, // nose face (blue) {{-.5f, -.5f, 0.5f}, {.1f, .1f, .8f}}, {{.5f, .5f, 0.5f}, {.1f, .1f, .8f}}, {{-.5f, .5f, 0.5f}, {.1f, .1f, .8f}}, {{.5f, -.5f, 0.5f}, {.1f, .1f, .8f}}, // tail face (green) {{-.5f, -.5f, -0.5f}, {.1f, .8f, .1f}}, {{.5f, .5f, -0.5f}, {.1f, .8f, .1f}}, {{-.5f, .5f, -0.5f}, {.1f, .8f, .1f}}, {{.5f, -.5f, -0.5f}, {.1f, .8f, .1f}} }; And my indices const auto indices = std::vector<sbx::uint32>{ 0, 1, 2, 0, 3, 1, 4, 5, 6, 4, 7, 5, 8, 9, 10, 8, 11, 9, 12, 13, 14, 12, 15, 13, 16, 17, 18, 16, 19, 17, 20, 21, 22, 20, 23, 21 }; Do you have any idears or hints where I sould look to solve this behaviour? Has this even to do with the pipeline or am I on the wrong path? Edit: Might that be a problem caused by vulkans coordiante system? And if so, how would I fix it?
Your problem has nothing to do with vertex order since you're not culling backfaces: .cullMode = VK_CULL_MODE_NONE, If you're trying to avoid setting up a depth test by just drawing front faces, you need to change this to .cullMode = VK_CULL_MODE_BACK_BIT, and then you'll either be able to see only the front faces, and won't have this overlapping issue. However, if your triangle winding is incorrect, the cube will look inverted.
73,166,228
73,166,482
How to solve this Coverity issue called OVERRUN
I write a C++ code as below and use Coverity to check it. Coverity report OVERRUN error of it, as attached picture shown. But I don't understand what does it mean and how to fix it. Any hint? wchar_t* GetMainAppPath() { const wchar_t* mainAppName = L"AIScreenshot.exe"; const wchar_t* agentName = L"AIScreenshotAgent.exe"; size_t lenOfMainApp = wcsnlen_s(mainAppName, MAX_PATH); size_t lenOfAgent = wcsnlen_s(agentName, MAX_PATH); Part of the error message: Event overrun-buffer-arg: Overrunning buffer pointed to by "mainAppName" of 17 2-byte elements by passing it to a function which accesses it at element index 259 (byte offset 519) using argument "260ULL".
But I don't understand what does it mean It's telling you that the call to wcsnlen_s is reading off the end of your string. I'm not going to transcribe the error from your picture of text, but you can read it for yourself. Your string is actually sixteen wchars (followed by a null wide character). You told wcsnlen_s that you had PATH_MAX characters, and just want to know where the null wide character is. But this is false, your string object doesn't have that many characters in the first place. ... how to fix it ... Either stop using a runtime calculation for something you know statically: const wchar_t mainAppName[] = L"AIScreenshot.exe"; // remember to subtract 1 for the null wide terminator size_t lenOfMainApp = (sizeof(mainAppName)/sizeof(*mainAppName)) - 1; ... or do the runtime calculation correctly: const wchar_t* mainAppName = L"AIScreenshot.exe"; // you know it's terminated, so there's no need to pass a length anyway size_t lenOfMainApp = wcslen(mainAppName); ... or if you really want to keep the original form (for no benefit whatsoever): size_t lenOfMainApp = wcsnlen_s(mainAppName, sizeof mainAppName / sizeof mainAppName[0]);
73,166,348
73,166,874
Is This The True Way To Implement Explicit Template Specialization Of Template Function In C++20
Hi I wrote that code for my c++ course assignment, it works but I don't know if it is best way to implement explicit specialization. I am waiting for your helps, thank you in advance. #include <iostream> template <typename T> T Max(const T* pArr, size_t arrSize) { T result{ pArr[0] }; for (size_t i = 0; i < arrSize; i++) { if (pArr[i] > result) result = pArr[i]; } return result; }; template<const char*> const char* Max(const const char** pArr, size_t arrSize) { const char* result{ pArr[0] }; for (size_t i = 0; i < arrSize; i++) { std::cout << strcmp(pArr[i], result) <<std::endl; if (strcmp(pArr[i],result)>0) result = pArr[i]; } return result; } /* Why that didn't work? That implementation gave us this error Error (active) E0493 no instance of overloaded function "Max" matches the specified type template<> const char* Max<const char*>(const const char** pArr, size_t arrSize) { const char* result{ pArr[0] }; for (size_t i = 0; i < arrSize; i++) { std::cout << strcmp(pArr[i], result) << std::endl; if (strcmp(pArr[i], result) > 0) result = pArr[i]; } return result; } */ int main(){ const char* carr[4]{"hello","world","RAM","ALU"}; std::cout<<Max(carr,4)<<std::endl; }
At very first: You are re-inventing the wheel, there's already std::max_element doing nearly (returning an iterator to, not the element itself) the same! Then to specialise a template you first need a base template and then the specialisation, for instance: // the base template: template <typename T> void demo (T const& t) { // do something with T } //the specialisation: template<> void demo<std::string>(std::string const& s) // explicit template arguments { // to something specific for std::string } // alternatively: template<> void demo(std::std::string const& s) // deduced template arguments { } You usually do so, though, only if unavoidable, e.g. some templated function calls yet another templated function with explicit template arguments and you need to adjust this other function for a specific type. Otherwise you would rather prefer overloading; in your case that could look like: template <typename T> T const& max(T const arr[], size_t size) { /* ... */ } // ^ // note that in the general variant I'd rather return a reference to avoid // unnecessary copies e.g. for `std::string` // note the missing template definition! // -> no template -> an OVERLOAD to the templates existing! char const* max(char const* const arr[], size_t size) { /* ... */ } // ^ can omit the reference, we have pointers anyway Yet a totally different alternative might be providing yet another template argument that specifies the comparison, just as std::max_element does, e.g. like template <typename T, typename Cmp = std::less<T>> T* max(T&, T&, Cmp const& = Cmp()) { /* ... */ } Instead of writing a separate function for finding the maximum you could now just provide a custom comparator: char const* s[] = { "hello", "world" }; auto m = max ( s, sizeof(s)/sizeof(*s), [](auto x, auto y) { return strcmp(x, y) < 0; } ); Now if you finally insist on the specialisation it would look like this: template <typename T T const& max(T const arr[], size_t size) { /* ... */ } // here with deduced template arguments: template<> char const*& max(char const* const arr[], size_t size) { /* ... */ } // ^ // now we need the reference (if you actually add as I proposed) // to remain compatible with the base template
73,166,509
73,167,227
Integer sequence as a non-type template parameter
I'd like to pass several arbitrary length integer sequences as non-type parameters to a template class, so the instantiation would look something like this: Foo<Bar, {1,2,3,4}, {5,6,7}> foo; Is there a simple way to do this, possibly with C++11? *** EDIT Ok, here's a more specific situation: #include <vector> using std::vector; void f(vector<int> const & vec1, vector<int> const & vec2) { // do something with vec1 and vec2 } template<MagicalSequenceType & seq1, MagicalSequenceType & seq2> struct Foo { Foo(){ f(vector<int>(seq1), vector<int>(seq2)); } }; main(){ // I want to be able to do something like this: // ideally with syntax this elegant but not necessary Foo < {1,2,3,4}, {5,6,7} > foo; } This is a bit on a pseudocode level. I guess MagicalSequenceType is what I'm after, be it an actual type or some syntactic template trickery :)
Here is an example on how to use arbitrary length integer sequences as template parameter in c++11. It requires a bit of template magic as we can see :P #include <array> #include <utility> #include <iostream> // Crude c++14 integer_sequence template<int...> struct ints { }; // Turn an integer sequence into a std::array template<int... Is> constexpr std::array<int, sizeof...(Is)> ints_to_array(ints<Is...>) { return std::array<int, sizeof...(Is)>{Is...}; } // Get the n'th sequence from a template parameter pack template<std::size_t Idx, class First, class... Sequences> struct get_n { static_assert(Idx < sizeof...(Sequences) + 1, "Idx must be in range"); using type = typename get_n<Idx - 1, Sequences...>::type; }; template<class First, class... Sequence> struct get_n<0, First, Sequence...> { using type = First; }; struct Bar { }; // The class needing multiple integer sequences template<class T, class... Sequences> struct Foo { void function_using_second_sequence() { using sequence = typename get_n<1, Sequences...>::type; constexpr auto vals = ints_to_array(sequence()); for (auto i : vals) { std::cout << i << " "; } std::cout << '\n'; } }; int main() { Foo<Bar, ints<1, 2, 3, 4>, ints<5, 6, 7>> foo; foo.function_using_second_sequence(); } Try it on godbolt EDIT: In c++20 it is much simpler :P #include <array> #include <iostream> #include <utility> template<std::size_t Idx, class First, class... Args> constexpr decltype(auto) get_n(First&& first, Args&& ...args) { if constexpr (Idx == 0) return std::forward<First>(first); else return get_n<Idx - 1>(std::forward<Args>(args)...); } template<class T, auto... Sequences> struct Foo { void function_using_second_sequence() { constexpr auto vals = get_n<1>(Sequences...); for (auto i : vals) { std::cout << i << " "; } std::cout << '\n'; } }; struct Bar { }; int main() { Foo<Bar, std::array{1, 2, 3, 4}, std::array{5, 6, 7}> foo; foo.function_using_second_sequence(); }
73,166,884
73,168,749
Partially specialized template static constexpr in template class
(A toy, minimal not-working example) The next code won't compile with cpp20/17: template<typename TSomeTemplate> struct A { static constexpr size_t B = 1; template<typename T, typename... Ts> static constexpr size_t C = 4; template<typename T> static constexpr size_t C<T> = B; }; int main() { A<int>::C<int>; return 0; } With the error of "Expression did not evaluate to constant" regarding the last line in the struct. However, it does compile with full specialization, or without referencing B: template<typename TSomeTemplate> struct Works { static constexpr size_t B = 1; template<typename T, typename... Ts> static constexpr size_t C = 4; template<> static constexpr size_t C<int> = B; }; template<typename TSomeTemplate> struct AlsoWorks { static constexpr size_t B = 1; template<typename T, typename... Ts> static constexpr size_t C = 4; template<typename T> static constexpr size_t C<T> = 2; }; Why is it so? How can I make the first struct work?
GCC and MSVC are wrong in rejecting the code as the program is well-formed. B is a constant expression and can be used as an initializer when initializing C during its partial specialization. This is a msvc bug reported here as: MSVC rejects valid code when using constexpr static data member as initializer. Moreover, we are allowed to provide a partial specialization for C(as you did). This is a gcc bug reported as: GCC rejects valid code involving partial specialization of variable template.
73,167,362
73,168,118
C++: In the switch I need to press twice to get a single input
I try to make a menu with ncurses library, I made a switch with a getch() that takes the input. When I'm moving in the menu I need to press twice the keys to get the right input. For example if I want to go to the "exit" line from "options" line I need to press twice the KEY_DOWN, if I press only one time the cursor doesn't move. This is the code: #include <iostream> #include <cstring> #include <ncurses.h> void start(){ initscr(); noecho(); raw(); cbreak(); } void position(WINDOW* win, int curr, char string1[], char string2[], char string3[]){ if(curr==1){ mvwaddstr(win, 7, 21, string2); mvwaddstr(win, 8, 21, string3); wattron(win, A_REVERSE); mvwaddstr(win, 6, 21, string1); wrefresh(win); } else if(curr==2){ mvwaddstr(win, 6, 21, string1); mvwaddstr(win, 8, 21, string3); wattron(win, A_REVERSE); mvwaddstr(win, 7, 21, string2); wrefresh(win); } else{ mvwaddstr(win, 6, 21, string1); mvwaddstr(win, 7, 21, string2); wattron(win, A_REVERSE); mvwaddstr(win, 8, 21, string3); wrefresh(win); } wattroff(win, A_REVERSE); } int main (){ start(); WINDOW * win = newwin (20, 50, 0, 0); refresh(); box (win, 0, 0); wrefresh(win); keypad(win, TRUE); int length = 20, current = 1; char string1[length], string2[length], string3[length]; strncpy(string1, "NEW GAME", 10); strncpy(string2, "OPTIONS", 10); strncpy(string3, "EXIT", 10); mvwaddstr(win, 7, 21, string2); mvwaddstr(win, 8, 21, string3); mvwaddstr(win, 6, 21, string1); wrefresh(win); while(getch()!='x'){ int push = wgetch(win); switch(push){ case KEY_UP: current--; if(current==0){ current=1; } break; case KEY_DOWN: current++; if(current==4){ current=3; } break; case 10: break; default: break; } position(win, current, string1, string2, string3); } getch(); endwin(); return 0; }
You call (w)getch twice in the loop: while(getch()!='x'){ int push = wgetch(win); // ... } Try this to get the character and check for the loop condition at the same time: int push; while ((push = wgetch(win)) != 'x'){ // ... }
73,167,680
73,167,821
Why are get/set functions used in C++ so often?
What is the point of doing this: class thing { public: void setMarbles(int _marbles){marbles = _marbles;} void getMarbles(){return marbles;} private: int marbles; }; when you can just do this: class thing { public: int marbles; }; I feel like this is a super common question, but I cant find an answer anywhere. My only theory is that if the order ov variables are changed in a new version of the class, programs that are using the old class will have the variables switched. Is this the correct reason?
Encapsulation, maintainability, debugability Consider: void thing::setMarbles(int _marbles) { // runtime error if incorrectly used assert(_marbles > 0); marbles = _marbles; } void thing::setMarbles(int _marbles) { // log to some file to debug some specific scenario someLogUtility("Marbles write", _marbles); marbles = _marbles; } You could also want to change thing in the future: private: char marbles; // support less marbles or private: long marbles; // support more marbles and then, you get to keep your setter without breaking external user code. It is a really good practice, but it takes some mileage on real projects to see the full value. The short of it is: a public field ties your hands forever. A setter leaves flexibility. Also, as suggested in comments: void thing::setMarbles(int _marbles) { // setting a breakpoint on next line is possible and lets you easily find where/when marbles is modified. marbles = _marbles; }
73,167,852
73,569,844
Instantiation of QAxObject from dumpcpp segfault with minGw C++ -o2 or -o3 flag
Qt version: 5.12.10 I wanted to interface with an application using the COM layer, this application was delivered with a .tlb file so I used Qt's dumpcpp to generate header and source file. To use the generated class, I first get an IUnknown from windows ROT and then instantiate the classes I need from a class I used an interface. My code looks like this : Code instantiating my class: //Initialize COM, load the ROT, get the monikers and for each monikers //Check if the monikers name is the one we want if (!wcsncmp(monikerDisplayName, appComIdentifier, wcslen(appComIdentifier))) { qDebug() << "Found app"; IUnknown *currentObject = nullptr; if (rot->GetObject(currentMoniker, &currentObject) == S_OK) { AppCommunication appCom(static_cast<app::IApplicationInterface *>(new QAxObject(currentObject))); } } The AppCommunication class: Header file: class AppCommunication : public IAppCommunication { public: AppCommunication(app::IApplicationInterface *applicationInterface); ~AppCommunication() override = default; private: app::appApplication appApplication; app::appJob appJob; }; cpp file: AppCommunication::AppCommunication(app::IApplicationInterface *applicationInterface) : appApplication(applicationInterface), appJob(static_cast<app::IJobInterface *>(new QAxObject(appApplication.CreateJobObject()))) // ^ // | // Segfault here { } All the classes under the app namespace are the ones generated by the dumpcpp tool. This works perfectly fine with the optimization flags -o0 or -o1 in the compiler but when I set -o2 or -o3 my program crashes. From what I could trace this is the instantiation of the appJob (not the fetching of the JobInterface) that causes the crash. I consider Qt's code and Qt's generated code to be robust/validated enough so I think this error must be me having an undefined behaviour. But I can not see what I did wrong here. EDIT: I managed to find a way to avoid the issue. What I have found is that if I use a pointer instead of the class by itself it works fine: Header file: class AppCommunication : public IAppCommunication { public: AppCommunication(app::IApplicationInterface *applicationInterface); ~AppCommunication() override = default; private: app::appApplication appApplication; app::appJob *appJob; }; cpp file: AppCommunication::AppCommunication(app::IApplicationInterface *applicationInterface) : appApplication(applicationInterface), appJob(new app::appJob(static_cast<app::IJobInterface *>(new QAxObject(appApplication.CreateJobObject())))) { } And this also work with a unique_ptr instead of the raw pointer so this is the route I will take. I am more and more starting to think this is a MinGW because I can't see what could cause an issue like that...
The mistake was on me. After getting the IUnknown * from the COM, we have to get a IDispatch * from it and then instantiate directly the classes: //Initialize COM, load the ROT, get the monikers and for each monikers //Check if the monikers name is the one we want if (!wcsncmp(monikerDisplayName, appComIdentifier, wcslen(appComIdentifier))) { qDebug() << "Found app"; IUnknown *currentObject = nullptr; if (rot->GetObject(currentMoniker, &currentObject) == S_OK) { //Add the get dispatch part IDispatch *currentObjectDispatch = nullptr; HRESULT hr = currentObject->QueryInterface(IID_IDispatch, (void **)&currentObjectDispatch); if (FAILED(hr)) { return; } //Get the interface directly without static cast AppCommunication appCom(new app::IApplicationInterface(currentObjectDispatch)); // Use the class instance with some method calls } } And do the same on the class we retrieve in the ctor: AppCommunication::AppCommunication(app::IApplicationInterface *applicationInterface) : appApplication(applicationInterface), appJob(new app::IJobInterface(appApplication.CreateJobObject())) { }
73,168,762
73,168,834
How can I call a function from a third party lib that is not marked constexpr from a constexpr function?
I want to do exactly what the title says. I have some third party code with an API. The information needed to evaluate the function should all be available at compile time to evaluate the function. However it does not appear the third party labeled it constexpr sadly. Furthermore, I don't have the source code for the full implementation, just headers for a lot of it. It seems it may use a shared object to evaluate the calls as a lot of things seem to be marked extern after drilling down into the API's header files. Due to these calls not being constexpr every time I try to invoke it for use in static_assert() compilation fails. How can I make this function run at compile time and use the result in my constexpr function to resolve the static_assert() condition? All the inputs are known at compile time. No external data should be needed.
First of all a function can only be called in a constant expression if its definition is available in the translation unit with the constant expression. That means that if the function definitions are not inline in the header, then it is impossible to call the function in a constant expression at all. If the function definitions are available inline in the header, then it is still impossible without modifying the header and adding constexpr. If you can't recompile the whole library with the modified header, then you'll just have to hope that the ODR violations don't break anything, but that is undefined behavior territory and no guarantee that there won't be subtle bugs resulting from this. Alternatively you could copy the code from the header file to re-implement all of the functions you want to have constexpr as constexpr functions in your own namespace and use these instead. If they are member functions of a class you would however get problems since you would need to re-implement the class as well and probably add a translation layer between the original and new class. Of course the only proper solution is to ask the supplier of the library to make the relevant functions constexpr-friendly and supply a new version of the library with those changes implemented.
73,168,909
73,169,028
Create CommandQueue and Command Allocator using IID_PPV_ARGS
I am learning how to create CommandQueue, Command Allocator, and CommandList in DirectX 12. However, a question arose in the process of creating each with the Create function. The following is the code from the major. ComPtr<ID3D12CommandQueue> mCommandQueue; ComPtr<ID3D12CommandAllocator> mDirectCmdListAlloc; ComPtr<ID3D12GraphicsCommandList> mCommandList; ThrowIfFailed(md3dDevice->CreateCommandQueue(&queueDesc,IID_PPV_ARGS(&mCommandQueue))); ThrowIfFailed(md3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,IID_PPV_ARGS(&mDirectCmdListAlloc.GetAddressof()))); If you look at this code, IID_PPV_ARGS and ComPtr pointer is used to create the CommandQueue. However, when creating a CommandAllocator, IID_PPV_ARGS and ComPtr's GetAddressof() are used. I don't understand why these two are different. I know that if I put &ComPtr in IID_PPV_ARGS, it is converted to COM ID and void** using __uuidof and IID_PPV_ARGS_Helper. What does it mean to put ComPtr.getAddressOf() instead of &ComPtr?
IID_PPV_ARGS() expects the address of an interface pointer variable. Both ComPtr::operator& and ComPtr::GetAddressOf() return such an address - the address of the internal ComPtr::ptr_ data member. The only difference between them is that ComPtr::operator& calls Release() on the current interface if it is not null, whereas ComPtr::GetAddressOf() does not (use ComPtr::ReleaseAndGetAddressOf() for that). However, that said, I would not expect IID_PPV_ARGS(&mDirectCmdListAlloc.GetAddressof()) to compile, for two reasons: ComPtr::GetAddressOf() returns a temporary variable, and C++ does not allow taking the address of a temporary. even if you could, ComPtr::GetAddressOf() returns a T** pointer, so taking its address would yield a T*** pointer, which is not what IID_PPV_ARGS() wants. It should be IID_PPV_ARGS(mDirectCmdListAlloc.GetAddressof()) instead, ie drop the &.
73,168,961
73,174,503
macOS Xcode, how to link/compile libvips as a static lib
I have a small app called Messer. It's a native macOS app using Swift and SwiftUI. The way the app works is by using the native macOS apis to manipulate the image (NSImage) and finally saves a png file to disk. Further conversion to other formats (with optimization) is left to embedded binaries of popular open source libraries. The problem is that the conversion and manipulation is too slow, for smallish images it's fine, but anything over a mb makes the app choke. I'm looking for ways to (radically) improve the performance and I came across libvips, it even has support for webp. So basically I would like to migrate all the image manipulation code to libvips. However, I'm a complete noob when comes to compilation toolchains and what not. Could anyone give me a hand and provide some detailed instructions on how would I go about embedding the library in my macOS Xcode project and further then get it to compile statically (due to all the dependencies it has). I would greatly appreciate it! Edit: I just realized libvips is GPL which means I cannot embed it without releasing the source code of my app. Which is something I do not want to do. I will leave the question open for future reference though, maybe someone needs it at some point.
A fully static library is difficult, and probably not necessary. libvips itself is easy to build static, but it has a lot of dependencies (it can be more than 40 other projects), and you'll need to make static versions of all those libraries too. It's a lot of very annoying work. Instead, I would use homebrew to build a vips area, and take a copy of that. Wipe your homebrew install area, do a fresh install, then brew install vips. Take a copy of the brew area, trim out stuff you don't need (there's a fair amount you can cut away, you probably only need lib and include, make a script to do this for you), and copy that tree into your project. You might need to set some environment variables like DYLD_LIBRARY_PATH to get it to link. You'll need to be careful that you don't include any licensed code. Poppler, for example, which libvips can use for PDF load, is GPL and you mustn't use that. It might be worth making your own libvips binary that only enables the dependencies you want. I have a repo here: https://github.com/jcupitt/build-osx That builds a macOS .app for this thing: https://github.com/libvips/nip2 It uses jhbuild to make the whole libvips stack from scratch and then package it. I don't think jhbuild is a a good solution for you directly, but you could probably adapt some of the packaging scripts.
73,169,352
73,169,648
Overload resolution of int vs std::vector<int> with an initializer list of a single int
Why does c++ choose a primitive type overload match over a "better" matching initializer list? #include <vector> void foo([[maybe_unused]] int i) {} void foo([[maybe_unused]] const std::vector<int>& v) {} int main() { foo(0); foo({1,2,3}); foo({0}); // calls foo(int) and issues a warning, // rather than what seems like the "better" // match foo(vector).. why? } <source>:10:9: warning: braces around scalar initializer [-Wbraced-scalar-init] foo({0}); // calls foo(int) and issues a warning, ^~~ Perhaps "surprising" result, since the compiler chooses the option for which it then issues a diagnostic? Using Clang 14 https://godbolt.org/z/1dscc5hM4
{0} doesn't have a type, so we need to try and convert it to the parameter types of the overload set. When considering void foo([[maybe_unused]] const std::vector<int>& v) {} We need to consult [over.ics.list]/7.2 which states Otherwise, the implicit conversion sequence is a user-defined conversion sequence whose second standard conversion sequence is an identity conversion. so we have a user defined conversion for this conversion sequence. Looking at void foo([[maybe_unused]] int i) {} We find the conversion covered in [over.ics.list]/10.1 which states if the initializer list has one element that is not itself an initializer list, the implicit conversion sequence is the one required to convert the element to the parameter type; The element in this case is 0, which is an integer literal which is an exact match standard conversion So now we have a user defined conversion vs a standard conversion and that is covered by [over.ics.rank]/2.1 a standard conversion sequence is a better conversion sequence than a user-defined conversion sequence or an ellipsis conversion sequence, and and now we know that the standard conversion is a better conversion and that is why the int overload is chosen over the std::vector<int> overload.
73,169,457
73,169,604
Is there an alternative to overloading or template specialization? I am attempting to call a specific function based on a template parameter
I have generated a simpler example of what I am trying to accomplish. I would like to be able to call a function, which returns a class containing two template parameters, based on one of the two templated parameters (Variance). My hierarchy can be simplified to this. template<typename T> class AbstractType {}; template<typename T, Variance Type> class BaseType : public AbstractType<T> {}; template<typename T, Variance Type> class FinalType : public BaseType<T, Type>{}; Where FinalType in this example isn't strictly necessary, it also inherits from other templated classes in my actual code, which serves no purpose in this example, so it's been removed. Here's the example code. enum class Variance { Interval, Weighted, Constant }; template<typename T> class AbstractType { protected: AbstractType(T* _Instance) : Instance(_Instance) {}; T* Instance; }; template<typename T, Variance Type> class BaseType : public AbstractType<T> { protected: BaseType(T* _Instance) : AbstractType<T>(_Instance) {}; }; template<typename T> class BaseType<T, Variance::Interval> : public AbstractType<T> { protected: BaseType(T* _Instance) : AbstractType<T>(_Instance) {}; int Interval; public: void SetInterval(int NewInterval) { Interval = NewInterval; } }; template<typename T> class BaseType<T, Variance::Weighted> : public AbstractType<T> { protected: BaseType(T* _Instance) : AbstractType<T>(_Instance) {}; int Weight; public: void SetWeight(int NewWeight) { Weight = NewWeight; } }; template<typename T, Variance Type> class FinalType : public BaseType<T, Type> { public: FinalType(T* _Instance) : BaseType<T, Type>(_Instance) {}; }; struct Interface { template<typename T> BaseType<T, Variance::Weighted>* CreateBaseInstance(T t, int Weight) { FinalType<T, Variance::Weighted>* OutObj = new FinalType<T, Variance::Weighted>(t); OutObj.SetWeight(Weight); return OutObj; } template<typename T> BaseType <T, Variance::Interval>* CreateBaseInstance(T t, int Interval) { FinalType<T, Variance::Weighted>* OutObj = new FinalType<T, Variance::Interval>(t); OutObj.SetInterval(20); return OutObj; } }; struct Object {}; void test() { Interface Inter; Object Obj; Inter.CreateBaseInstance<Object, Variance::Weighted>(Obj, 50); // Too many template arguments Inter.CreateBaseInstance<Object, Variance::Interval>(Obj, 10); // Too many template arguments Inter.CreateBaseInstance<Object>(Obj, 50); // More than one instance of overloaded function Inter.CreateBaseInstance<Object>(Obj, 10); // More than one instance of overloaded function } Additionally, Object being used as the first template is just for testing purposes. I will not know the type in this codebase. I've been able to resolve this problem by creating multiple functions such as.. template<typename T> BaseType<T, Variance::Interval>* CreateIntervalInstance(T t, int Interval)… template<typename T> BaseType<T, Variance::Weighted>* CreateWeightedInstance(T t, int Weight)… template<typename T> BaseType<T, Variance::Constant>* CreateConstantInstance(T t)… However, as mentioned earlier, FinalType inherits from another set of classes, so while the above works, it becomes crowded and unsustainable with the number of functions needed to do the simple tasks above. I have experimented with making the Interface have a template parameter, such as.. // Base Class template<Variance Variant> class Interface… // Specialized template<> class Interface<Variance::Interval>… // Functions to create Interval Instances //Specialized template<> class Interface<Variance::Weighted>… // Functions to create Weighted Instances But, I once again run into it becoming unsustainable. The last thing I am currently looking into is Type Traits, but am unsure if or how that could be implemented to make this simpler.
Without following all of it really in detail, don't you just want e.g. template<typename T, Variance Type> auto CreateBaseInstance(T t, int value) { // Instead of `auto` maybe `std::unique_ptr<BaseType<T, Type>>` auto OutObj = std::make_unique<FinalType<T, Type>>(t); if constexpr(Type == Variance::Weighted) { OutObj->SetWeight(value); } else if constexpr(Type == Variance::Interval) { OutObj->SetInterval(value); } return OutObj; } (I replaced new with std::make_unique, because using raw new like this is generally considered bad practice due to the memory management problems it causes.)
73,169,671
73,171,920
Is it possible to truncate C preprocessor identifiers?
In C, with #define, we can use the token pasting operator ## to concatenate an identifier with some other text. Is it possible to do the reverse as seen in the example below? #define millimeter //truncate to milli //convert to millisecond I am specifically trying to use this for function name generation, so a call to a non-existent function millimeter() can generate code containing millisecond. The previous paragraph is an example of how I would use this. I have included it for context, but I am not sure if that is possible even if the identifier can be truncated. If you can link related questions for this part, that would be helpful. Edit: Most of you are right, this is definitely an XY issue. What I was hoping was that if someone tries to use the function millisecond(), it would auto-generate code which needed to contain millimeter(). I realize this isn't possible, so now I have a macro like #define TIME_FUNC_DEFINE(unit) function_definition. It is used like TIME_FUNC_DEFINE(millis) which will create both millisecond and millimeter as needed.
The units of input to the C preprocessor are (preprocessing) tokens such as identifiers, operators, and string literals. Tokens are atomic as far as the preprocessor is concerned -- it has no mechanism for dividing them into pieces or for operating in any other way on partial tokens. Under some circumstances, you can use macro substitution to emulate truncation of a pre-selected (by you) set of specific tokens that have the form of identifiers or keywords, but this is not generalizable. I am specifically trying to use this for function name generation Where this sort of thing is done, it is generally done by pasting tokens together, not truncating them.
73,169,877
73,169,971
How to insert a new node at any given position in linked list?
Kindly check my code below. I am not getting the actual output when I run this program. What I want to do is to insert a new node at the position entered by the user. I have tested this code by entering 5 values for 5 nodes i.e 1,2,3,4,5 and then I entered position 2 to insert a value 8, but when I display it, it gives all other values except the value that I entered at the specific position. #include<iostream> using namespace std; class Node { public: int data; Node* next; }; int main() { int choice, pos, count = 0, i = 1; Node* head, *newnode, *temp; head = 0; do { count++; newnode=new Node(); cout<<"Enter data:"; cin>>newnode->data; newnode->next=0; if(head==0) head=temp=newnode; else { temp->next=newnode; temp=newnode; } cout<<"Do you want to create a new node... press 0 for no and 1 yes:"; cin>>choice; }while(choice==1); cout<<"Enter position:"; cin>>pos; if(pos>count) { cout<<"Invalid position\n"; } else { temp=head; while(i<pos) { temp=temp->next; i++; } cout<<"Enter data you want to insert:"; newnode=new Node(); cin>>newnode->data; newnode=temp->next; temp->next=newnode; } temp=head; while(temp!=0) { cout<<temp->data; temp=temp->next; } }
Your problem is here: cout<<"Enter data you want to insert:"; newnode=new Node(); cin>>newnode->data; newnode=temp->next; temp->next=newnode; newnode=temp->next makes newnode equal to 0, then temp->next=newnode makes temp->next equal to zero. Perhaps you meant to write newnode->next = temp->next instead?
73,170,075
73,170,136
using std::launch::deferred does not defer the function in std::async
https://godbolt.org/z/MEsandWGe Here's the code I'm testing, same as the above godbolt link: #include <future> #include <string> #include <iostream> #include <chrono> #include <thread> using namespace std::chrono_literals; int main() { int v = 0; auto a1 = std::async( std::launch::async | std::launch::deferred, [&v]() { std::cout << "begin 1" << std::endl; std::cout << "v = " << v << std::endl; std::this_thread::sleep_for(100ms); std::cout << "end 1" << std::endl; }); auto a2 = std::async( std::launch::async | std::launch::deferred, [&v]() { std::cout << "begin 2" << std::endl; std::this_thread::sleep_for(200ms); v = 123; std::cout << "end 2" << std::endl; }); a2.wait(); // My understanding is a1 does not run until here? // thus v should print 123 instead of 0 ? a1.wait(); return 0; } If I remove the async policy, it works as expected. The question is, why do I see a1 running concurrently with a2 and see v printed as 0? Does the async policy affect the behavior of deferred?
std::launch::async | std::launch::deferred means that std::async can choose which of the two policies is selected. It is implementation defined which one is used but it looks like your standard library chooses async rather than deferred.
73,170,352
73,170,393
Does the pointer in a class get deleted when the class gets deleted/destroyed?
I'm new to C++, and I want to know, does a pointer gets automatically deleted when the class gets deleted / destroyed? Here is an example: class A { public: Object* b; }; Will b get `deleted when the class is deleted?
The object that the pointer points to will not be deleted. That is why it is a bad idea to use a raw pointer to refer to an object created with dynamic storage duration (i.e. via new) like this if the class object is intended to be responsible for destroying that object. Instead use std::unique_ptr: #include<memory> //... class A { public: std::unique_ptr<Object> b; }; And instead of new Object(/*args*/) use std::make_unique<Object>(/*args*/) to create the object and a smart pointer to the object to store to b. Or, most likely, there is no reason to use a pointer indirection at all. You can have a Object directly in the class. (This only really doesn't work if Object is meant to be polymorphic.)
73,170,389
73,170,483
A question about dynamic memory allocation
Consider the portion of code below (please do not care about deleting the firstArray and secondArray): int *firstArray = new int[10]; int *secondArray = new int[20]; firstArray = secondArray; I have three questions here: Is the expression firstArray = secondArray; safe even though they have two different sizes? ps: It seems the compiler (code::blocks) does not complain. Now that firstArray and secondArray have the same address, what happens if I delete one of the arrays, is the other one deleted too? Why, when I delete the second one, the application crashes.
Okay, let's talk about what you're doing here. Is it safe? Yes. But it's a mistake because you have orphaned the data that secondArray used to point to. They now point to the same space in memory. Imagine that firstArray holds the memory address 0x1000 and secondArray holds address 0x2000. After this assignment, they both hold 0x1000, and 0x2000 is orphaned. If you delete [] firstArray, then continuing to reference 0x1000 by either pointer can lead you into trouble. You're going to step all over who knows what. You've now engaged in undefined behavior, and crashes are common when you engage in undefined behavior. Now, here's some opinion. It's important to understand the underlying memory systems, but once you do, start using various smarter containers. You can use std::array instead, for instance, and then you don't have to deal with memory allocation at all. This eliminates huge classes of bugs.
73,170,931
73,174,028
GLM perspective matrix ruins rendering
I created a projection matrix for Vulkan renderer using GLM, but after multiplying it with vertex itself in vertex shader, nothing renders. I have defined GLM_FORCE_RADIANS and GLM_FORCE_DEPTH_ZERO_TO_ONE (to be fine, I tried without both of these, or without one of these). Also I tried to pass fovy param as degrees or radians, but it didn't help. In addition, I noticed that orthographic matrix works just fine! Here's my code of vertex shader, matrix creation itself and front face is CCW (if it can help), depth testing disabled (didn't implement that yet): Projection matrix creation: glm::mat4 projection = glm::perspective(45.0f, 16.0f / 9.0f, 0.1f, 100.0f); glm::mat4 model = glm::mat4(1.0f); model = glm::rotate(model, (float)glfwGetTime() * 30, glm::vec3(0.0f, 0.0f, 1.0f)); Vertex Shader: #version 460 core layout(location = 0) in vec2 aPos; layout(location = 1) in vec3 aColor; layout(push_constant) uniform MVP { mat4 VP; mat4 Transform; } matrices; layout(location = 0) out vec4 Color; void main() { gl_Position = matrices.VP * matrices.Transform * vec4(aPos, 1.0f, 1.0f); Color = vec4(aColor, 1.0f); } The way I include GLM: #define GLM_FORCE_RADIANS #define GLM_FORCE_DEPTH_ZERO_TO_ONE #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp>
I fixed it. The "problem" was that projection and perspective division maps the [-near, -far] range to [-1, 1], which lead to flipping Z coordinate. Meanwhile I had Z coordinate as 10.0f, it was actually behing the camera. Solution was setting up Z coordinate value as -10.0f, which will be flipped to 10.0f after projection.
73,171,392
73,171,626
flex/bison gives me a syntax error after printing the result and if another input is written to work
After running the compiler and type the entry on, works fine. Then if I type another entry (and if it also works ok) it gave me Syntax Error. I must mention I am a new in ​​the world of flex/bison. To be honest I do not know what's could be wrong, some one please help? Here is my lex code: %{ #include <stdio.h> #include "calc.tab.h" void yyerror(char *); %} %option noyywrap DIGIT -?[0-9] NUM -?{DIGIT}+ %% {NUM} { yylval = atoi(yytext); return NUMBER; } [-()+*/;] { return *yytext; } "evaluar" { return EVALUAR; } [[:blank:]] ; \r {} . yyerror("caracter invalido"); %% and here it is my bison code: %{ #include <stdio.h> int yylex(void); void yyerror(char *s); %} %token NUMBER EVALUAR %start INICIO %left '+' '-' %left '*' '/' %% INICIO : EVALUAR '(' Expr ')' ';' { printf("\nResultado=%d\n", $3); } ; Expr : Expr '+' Expr { $$ = $1 + $3; } | Expr '-' Expr { $$ = $1 - $3; } | Expr '*' Expr { $$ = $1 * $3; } | Expr '/' Expr { $$ = $1 / $3; } | NUMBER { $$ = $1; } ; %% int main(){ return(yyparse()); } void yyerror(char *s){ printf("\n%s\n", s); } int yywrap(){ return 1; } Here is an example of the output: C:\Users\Uchih\Desktop\bison>a evaluar(2+3); Resultado=5 evaluar(3+2); syntax error
Your parser is written to accept a single input INICIO rule/clause, after which it will expect an EOF (and will exit after it sees it). Since instead you have a second INICIO, you get a syntax error message. To fix this, you want your grammar to accept one or more things. Add a rule like this: input: INICIO | input INICIO ; and change the start to %start input
73,172,098
73,172,337
How to conditionally get template type of multiple base class with multiple inheritance
This is NOT a duplicate of link Consider the following code: #include <type_traits> template <typename... Bases> struct Overloads : public Bases... {}; template <typename T> struct A { using AType = T; }; template <typename T> struct B { using BType = T; }; template <typename T> struct C { using CType = T; }; template <typename OverloadsType> struct Derived : public OverloadsType { }; int main() { // OK static_assert(std::is_same_v<typename Derived<Overloads<A<int>, B<float>, C<char>>>::AType, int>); // OK static_assert(std::is_same_v<typename Derived<Overloads<A<int>, B<float>, C<char>>>::BType, float>); // OK static_assert(std::is_same_v<typename Derived<Overloads<A<int>, B<float>, C<char>>>::CType, char>); // ??? static_assert(std::is_same_v<typename Derived<Overloads<B<float>, C<char>>>::AType, void>); } Demo: Link For the last line, I need to detect that Derived<Overloads<B<float>, C<char>>> is NOT derived from A, so I want typename Derived<Overloads<B<float>, C<char>>>::AType to be void or something (it fails to compile) How can I do this?
My precise use case is: 1. Determine if Derived is derived from A<T> for some T. 2. If so, figure out that T. With C++20 concepts, this isn't too difficult. You need a function that takes A<T> as a parameter. There need not be a function definition; we're just using template argument deduction. It will never be called: template<typename T> T getDerivedFromAType(A<T> const&); //Not implemented, since we will never call it. Any type U for which getDerivedFromAType(u) works will either be an A<T> itself or a type derived from A<T> (from a single A<T> of course). So we can build a concept out of it: template<typename U> concept IsDerivedFromA = requires(U u) { getDerivedFromAType(u); }; So long as nobody writes an overload of getDerivedFromAType, you're fine. This function ought to be in a detail namespace or have something else that lets people know that it is off-limits. To get the actual T used by A... well, there's a reason why the function returned T. We simply need a using statement that calculates the return type of the function call: template<IsDerivedFromA T> using BaseAType = decltype(getDerivedFromAType(std::declval<T>())); Notice that the template is guarded by our concept.
73,172,193
73,180,292
Can you static_cast "this" to a derived class in a base class constructor then use the result later?
We ran into this scenario in our codebase at my work, and we had a big debate over whether this is valid C++ or not. Here is the simplest code example I could come up with: template <class T> class A { public: A() { subclass = static_cast<T*>(this); } virtual void Foo() = 0; protected: T* subclass; }; class C : public A<C> { public: C(int i) : i(i) { } virtual void Foo() { subclass->Bar(); } void Bar() { std::cout << "i is " << i << std::endl; } private: int i; }; int main() { C c(5); c.Foo(); return 0; } This code works 100% of the time in practice (as long as the template parameter type matches the subclass type), but if we run it through a runtime analyzer, it tells us that the static_cast is invalid because we're casting this to a C* but the C constructor hasn't run yet. Sure enough, if we change the static_cast to a dynamic_cast, it returns nullptr and this program will fail and crash when accessing i in Bar(). My intuition is that it should always be possible to replace static_cast with dynamic_cast without breaking your code, suggesting that the original code in fact is depending on compiler-specific undefined behavior. However, on cppreference it says: If the object expression refers or points to is actually a base class subobject of an object of type D, the result refers to the enclosing object of type D. The question being, is it a base class subobject of an object of type D before the object of type D has finished being constructed? Or is this undefined behavior? My level of C++ rules lawyering is not strong enough to work this out.
In my opinion this is well-defined according to the current wording of the standard: the C object exists at the time of the static_cast, although it is under construction and its lifetime has not yet begun. This would seem to make the static_cast well-defined according to [expr.static.cast]/11, which reads in part: ... If the prvalue of type “pointer to cv1 B” points to a B that is actually a base class subobject of an object of type D, the resulting pointer points to the enclosing object of type D. Otherwise, the behavior is undefined. It doesn't say that the D object's lifetime must have begun. We might also want to look at the explicit rule about when it becomes legal to perform an implicit conversion from derived to base, [class.cdtor]/3: To explicitly or implicitly convert a pointer (a glvalue) referring to an object of class X to a pointer (reference) to a direct or indirect base class B of X, the construction of X and the construction of all of its direct or indirect bases that directly or indirectly derive from B shall have started and the destruction of these classes shall not have completed, otherwise the conversion results in undefined behavior. To form a pointer to (or access the value of) a direct non-static member of an object obj, the construction of obj shall have started and its destruction shall not have completed, otherwise the computation of the pointer value (or accessing the member value) results in undefined behavior. According to this rule, as soon as the compiler starts constructing the base class A<C>, it is well-defined to implicitly convert from C* to A<C>*. Before that point, it results in UB. The reason for this, basically, has to do with virtual base classes: if the path by which A<C> is inherited by C contains any virtual inheritance, the conversion may rely on data that are set up by one of the constructors in the chain. For a conversion from base to derived, if there is indeed any virtual inheritance on the chain, static_cast will not compile, so we don't really need to ask ourselves the question, but are those data sufficient for going the other way? I really can't see anything in the text of the standard, nor any rationale, for the static_cast in your example not being well-defined, nor in any other case of static_casting from base to derived when the reverse implicit conversion (or static_cast) would be allowed (excepting the case of virtual inheritance, which as I said before, leads to a compile error anyway). (Would it be well-defined to do it even earlier? In most cases this won't be possible; how could you possibly attempt to static_cast from B* to D* before the conversion from D* to B* is allowed, without having obtained the B* pointer precisely by doing the latter? If the answer is that you got from D* to B* through an intermediate base class C1 whose constructor has started, but there is another intermediate base class C2 sharing the same B base class subobject and its construction hasn't started yet, then B is a virtual base class, and again, this means the compiler will stop you from then trying to static_cast from B* back down to D*. So I think there are no issues left to resolve here.)
73,172,507
73,172,783
How to use cv::Mat::at<double>(i,j,k) (to access a multi channel matrix)?
#include <iostream> #include <opencv2/highgui/highgui.hpp> int main() { double m[1][4][3] = { {{1.0, 2.0, 3.0}, {4.0, 5.0, 6.0}, {7.0, 8.0, 9.0}, {10.0, 11.0, 12.0}}}; cv::Mat M(1, 4, CV_64FC3, m); for (int i = 0; i < 1; ++i) for (int j = 0; j < 4; ++j) for (int k = 0; k < 3; ++k) std::cout << M.at<double>(i, j, k) << std::endl; cv::namedWindow("Input", cv::WINDOW_NORMAL); cv::imshow("Input", M); cv::waitKey(); return 0; } Expected Output 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0 12.0 Current Output 1 8.10465e-320 5.31665e-315 4 8.11058e-320 2.122e-314 7 8.11355e-320 -9.44163e+21 10 7.16685e-308 0
opencv treats the number of channels in each element of a cv::Mat as separate from the number of dimensions. In your case cv::Mat M(1, 4, CV_64FC3, m) is a 2 dimensional array where each element has 3 channels. cv::Mat::at returns an element in the cv::Mat. In order to use it in your case you need to: Pass 2 indices for the 2 dimensions. Get a cv::Vec3d value which holds an element with 3 channels of doubles . Iterate over the channels using operator[] of cv::Vec3d. Complete example: #include <opencv2/core/core.hpp> #include <iostream> int main() { double m[1][4][3] = {{{1.0, 2.0, 3.0}, {4.0, 5.0, 6.0}, {7.0, 8.0, 9.0}, {10.0, 11.0, 12.0}} }; cv::Mat M(1, 4, CV_64FC3, m); for (int i = 0; i < M.rows; ++i) { for (int j = 0; j < M.cols; ++j) { cv::Vec3d const& elem = M.at<cv::Vec3d>(i, j); for (int k = 0; k < 3; ++k) { std::cout << elem[k] << std::endl; } } } return 0; } Output: 1 2 3 4 5 6 7 8 9 10 11 12 Note: Using cv::Mat::at for traversing a big matrix is not the most efficient way (and in debug builds it also incurs expensive validity checks). A more efficient way it to use cv::Mat::ptr, which gives you direct access to row data. Usage in your case (yields the same output): #include <opencv2/core/core.hpp> #include <iostream> int main() { double m[1][4][3] = { {{1.0, 2.0, 3.0}, {4.0, 5.0, 6.0}, {7.0, 8.0, 9.0}, {10.0, 11.0, 12.0}} }; cv::Mat M(1, 4, CV_64FC3, m); for (int i = 0; i < M.rows; ++i) { //----------------------------vvv--------------- cv::Vec3d const* pRow = M.ptr<cv::Vec3d>(i); for (int j = 0; j < M.cols; ++j) { cv::Vec3d const& elem = pRow[j]; for (int k = 0; k < 3; ++k) { std::cout << elem[k] << std::endl; } } } return 0; }
73,172,543
73,172,649
Type traits `is_noexcept`, `add_noexcept`, and `remove_noexcept`?
Motivation: In the implementation of P0288 std::move_only_function, I'd like to write a non-allocating special case for conversion from move_only_function<int() noexcept> to move_only_function<int()>: move_only_function<int() noexcept> f = []() noexcept { return 42; }; move_only_function<int()> g = std::move(f); // should just copy the bits I want to write, like, if constexpr (is_noexcept_version_of<HisSignature, MySignature>::value) { ... } I wanted to implement that type trait like this: template<class, class> struct is_noexcept_version_of : std::false_type {}; template<class Tp> struct is_noexcept_version_of<Tp noexcept, Tp> : std::true_type {}; but no vendor accepts that; they all think Tp noexcept is a syntax error. Question: How would you write this kind of type-trait without a combinatorial explosion of partial specializations, i.e. without exhaustively going through all the possible combinations of &, &&, const, etc.? Is it possible to write simple closed-form type traits for is_noexcept_v<T>, add_noexcept_t<T> and remove_noexcept_t<T>?
Aside from qualification conversions, the only possible implicit conversions between pointer-to-function types are the ones that remove noexcept and similarly for pointers-to-member-functions (except for base-to-derived conversion), so I think the following should work struct C {}; template<class A, class B> struct is_noexcept_version_of : std::bool_constant< requires { requires std::is_convertible_v<A C::*, B C::*>; requires std::is_function_v<A>; requires !std::is_same_v<A, B>; }> {};
73,172,791
73,178,560
How to dynamically create a lot of data for INSTANTIATE_TEST_CASE_P parameterized unit tests
I need help with INSTANTIATE_TEST_CASE_P(prefix, test, testing::ValuesIn(container)). Running VS 2022 and latest google test ("Microsoft.googletest.v140.windesktop.msvcstl.static.rt-dyn" version="1.8.1.5") The problem is, INSTANTIATE_TEST_CASE_P appears to only use the data in the container at compile time. I've tried everything to add more at runtime, before any tests run, without success (e.g., using SetUpTestSuite and SetUpEnvironment as mentioned google test docs This is actually a big problem. I have a lot of test data, too much to embed in the code without dramatically slower build times and warnings about “too much stack data, use the heap”. The sample code below shows the problem. Allocate two global vectors, one populated at compile time the other populated at runtime. Even though testing::Environment::SetUp is populating one vector with additional data, INSTANTIATE_TEST_CASE_P is only using the contents found at compile time. Am I missing something stupid simple? Is there another way to load a container so INSTANTIATE_TEST_CASE_P will use it? TestData.h struct TestData { std::string str_;}; extern std::vector<TestData>* g_data_in_code; extern std::vector<TestData>* g_data_in_file; TestData.cpp //First approach, global pointer and initializer list for data std::vector<TestData>* g_data_in_code = new std::vector<TestData> { TestData{"1"}, TestData{"2"} }; //Second approch, global pointer and load data during Environment SetUp std::vector<TestData>* g_data_in_file = new std::vector<TestData> { TestData{"3"}//added one element so google test will not skip empty container }; void LoadTestData(std::vector<TestData>* test_data) { ...just reads a text file line by line adding N number of TestData... } As recommended in google test docs, use my own main() instead of using gtest_main() and subclass Environment and implement SetUp to load test data prior to google test Environment start up. class MyTestEnvironment : public ::testing::Environment { public: ~MyTestEnvironment() override {} void SetUp() override { LoadTestData(g_data_in_file); //N more elements added } }; int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); auto* env = testing::AddGlobalTestEnvironment(new MyTestEnvironment); return RUN_ALL_TESTS(); } The actual Test.cc is simply class ParamTest : public ::testing::TestWithParam<TestData>{}; TEST_P(ParamTest,OneParamTest) { EXPECT_TRUE(1 == 1); //Interestingly, g_data_in_file->size() is N, but only 1 test //will run because, again, at compile time it contained 1 TestData not N } //3 passing tests INSTANTIATE_TEST_CASE_P(TestsFromCode, ParamTest, testing::ValuesIn(*g_data_in_code)); //1 passing test, instead of N passing tests (the number loaded by SetUp) INSTANTIATE_TEST_CASE_P(TestsFromFile, ParamTest, testing::ValuesIn(*g_data_in_file));
The generator expressions (including parameters to the generator) are evaluated in InitGoogleTest(). Therefore, it is necessary to read the data and put it to g_data_in_file before InitGoogleTest() is called in main function. And Environment::SetUp() is called only from RUN_ALL_TESTS(). So, it's too late to read the data for the parameterized test in Environment::SetUp(). But you can change a little bit the LoadTestData() function: ... std::vector<TestData> LoadTestData() { std::vector<TestData> test_data; //...just reads a text file line by line adding N number of TestData... return test_data; } ... INSTANTIATE_TEST_CASE_P(TestsFromFile, ParamTest, testing::ValuesIn(LoadTestData())); and it will work as expected.
73,172,806
73,181,022
Function Pointer using "typedef" keyword with Function Address stored as Variable? (C++ 14, VS 2019)
Problem Summary I'm attempting to create a callable function pointer inside of a function using templates for its return value and its arguments using C++ 14. I want the callable function pointer to return the templated type, and accept templated arguments. However, I also want the callable function pointer to point to an existing function at the address provided in an argument as an integer. This I am unsure of how to do. Below is an illustration of my current incomplete code: template <class retTempl, class argTempl_1, class argTempl_2> retTempl TEST_1(argTempl_1 value1, argTempl_2 value2, int addr) { typedef retTempl(*TEST_2)(argTempl_1, argTempl_2); return TEST_2(value1, value2); } In this case, TEST_2 is the new function pointer that I want to call, and the addr argument is the address of an existing function that I want the TEST_2 pointer to point to. The current error that the VS 2019 compiler throws at me is the following: Error C2440 '<function-style-cast>': cannot convert from 'initializer list' to 'operationFunction' I am unsure of exactly what it's trying to tell me, researching this error online leads to several possible causes, not all of which necessarily have to do with function pointers. However, this error may not even be relevant, as I have not been able to implement the function address yet. That is mostly what I want to focus on here. My Attempts I know that in order to make a function pointer created with the typedef keyword point to an actual function, you need to set the pointer variable equal to whichever function you want the pointer to point to. So for instance (example from https://www.section.io/engineering-education/function-pointers-in-c++/): int add(int x ,int y) { return x + y; } int main() { int (*funcptr)(int, int); funcpointr = add; ... } However, here the function that I want the TEST_2 pointer to point to is different every time that TEST_1 is called, with a different return value and arguments. Therefore, I cannot simply set the TEST_2 variable equal to the addr argument: template <class retTempl, class argTempl_1, class argTempl_2> retTempl TEST_1(argTempl_1 value1, argTempl_2 value2, int addr) { typedef retTempl(*TEST_2)(argTempl_1, argTempl_2); TEST_2 = addr; return TEST_2(value1, value2); } as this now supplies me with an additional VS error: Error C2513 'retTempl (__cdecl *)(argTempl_1,argTempl_2)': no variable declared before '=' I would assume that I would require another pointer variable here, perhaps from a list of function pointers that I want the TEST_2 variable to point to, but at this point I would like to hear a second opinion before I resume. Is what I'm trying to achieve here even possible to do with C++? Is there a different way that this should be done that I'm not aware of? Thank you in advance for reading my post, any guidance is appreciated!
After a lot of research, and posting this question on other programming forums, I reached an answer, and several other conclusions that I believe are worth sharing in regards to my original problem (very informative answers provided to me on this forum: https://cplusplus.com/forum/general/284539/). Immediate Solution The immediate issue in my original code was the fact that I mistakenly assumed that the typedef keyword creates an object, instead of an object type. What should have been done was to create an object instance of the type created with the typedef keyword (huge thanks to the people in the comments of my original post here for pointing this out). So: TEST_2 test_function; Following the creation of the object instance with the type of the function pointer, I have the argument addr of type int that holds the address of the function I want the TEST_2 pointer variable to point to. While the use of variables of size int isn't the best way to store function addresses (as int isn't large enough to store all formats of function addresses, and could result in other issues with the pointer), if you are forced to retrieve your function from an int variable, then you would need to typecast the address variable to your function pointer type in the variable you have created. So: TEST_2 test_function = (TEST_2)(addr); or TEST_2 test_function = reinterpret_cast<TEST_2>(addr); So the whole original function being: template <class retTempl, class argTempl_1, class argTempl_2> retTempl TEST_1(argTempl_1 value1, argTempl_2 value2, int addr) { typedef retTempl(*TEST_2)(argTempl_1, argTempl_2); TEST_2 test_function = (TEST_2)(addr); return test_function(value1, value2); } This now worked on my end to call my desired function, and to return the correct variable and type. However... Proper Solution As stated previously, using a variable of size int is not ideal for storing function addresses. There is a variable type designed to store addresses, uintptr_t, however this type of variable is only designed to store object addresses, not function ones. The proper way to do this would be to always store your function pointers exclusively as pointer types, such as void(*)(), to avoid any discrepancies with the function addresses. If there really is a need to store function addresses in variables, then it would be ideal to use memcpy, instead of casting, to achieve this (although I have not experimented with this as of now). Thank you to everyone who helped me out with this issue!
73,173,100
73,173,115
How can i access Array declared in one switch case and use it in another switch case C++
Im trying to create a menu driven program to perform operations on an array , I'm trying to figure out how to access variables from one switch statement to another. [I am a noob] This is the program #include <iostream> using namespace std; int main() { int c,a=0; do { cout << "-----MENU------" << endl; cout << "1.Create" << endl; cout << "2.Display" << endl; cout << "3.Insert" << endl; cout << "4.Delete" << endl; cout << "5.Search" << endl; cout << "6.Exit" << endl; cin >> c; switch(c) { case 1: { cout << "Enter the size of array :"; int s; cin >> s; a=s; int myarray[s]; for(int i=0;i<s;i++) { cout<<"Enter "<<i+1<<" element :"; cin>>myarray[i]; } } case 2: { if(a==0) { cout<<"Array is empty"<<endl; } else() } case 3: { } } }while(1);
Your first problem is that int array[s]; is not legal C++. It's a variable length array which is legal in C but not in C++. The C++ solution is to use a vector. #include <vector> std::vector<int> array; switch (c) { case 1: { cout << "Enter the size of array :"; int s; cin >> s; array.resize(s); ... } case 2: if (array.empty()) { cout<<"Array is empty"<<endl; } ... }
73,173,317
73,244,778
"Missing argument in parameter list" error while creating .dll file from the .o file
Am just starting learn jni and decided to do a hello world. i created a helloworld java file whose code is public class HelloWorld { public native void displayHelloWorld(); static{ System.loadLibrary("hello"); } public static void main(String[] args){ new HelloWorld().displayHelloWorld(); } } and i compiled it to get the following header file /* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class HelloWorld */ #ifndef _Included_HelloWorld #define _Included_HelloWorld #ifdef __cplusplus extern "C" { #endif /* * Class: HelloWorld * Method: displayHelloWorld * Signature: ()V */ JNIEXPORT void JNICALL Java_HelloWorld_displayHelloWorld (JNIEnv *, jobject); #ifdef __cplusplus } #endif #endif followed by creating a c file whose code is #include<jni.h> #include "HelloWorld.h" #include <stdio.h> JNIEXPORT void JNICALL Java_HelloWorld_displayHelloWorld(JNIEnv *env, jobject obj){ printf("Hello World \n"); return; } and compiled it to create the helloworld.o file and now when i tried to create the .dll file using the command gcc -shared -o hello.dll HelloWorld.o -Wl,--add-stdcall-alias i get this error At line:1 char:42 + gcc -shared -o hello.dll HelloWorld.o -Wl,--add-stdcall-alias + ~ Missing argument in parameter list. + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : MissingArgument what am i missing?
The problem is that in PowerShell comma has a special meaning of comma operator unlike, e.g., in Bash, where in such context there is no any special meaning to it. When your command is parsed, -Wl is considered a parameter name and , is interpreted to form an array (parameter list) as its argument. As seen in linked documentation, , is necessarily binary operator unless in expression mode, whereas for command invocation argument mode is used. But there's no left argument for this comma, thus Missing argument in parameter list error. To solve this, you can change the command to make PowerShell stop intepreting , in a special way by making -Wl,--add-stdcall-alias a quoted string using one of the types of strings. For our simple case any string type would do, e.g. with single-quoted strings we have: gcc -shared -o hello.dll HelloWorld.o '-Wl,--add-stdcall-alias' Another option is to use stop parsing token --%: gcc --% -shared -o hello.dll HelloWorld.o -Wl,--add-stdcall-alias
73,173,328
73,210,001
In C++ can I create a Binary Search Tree using objects/structs as the node?
In other related c++ work I managed to create a sort of binary search tree template. The implication here is that using this template, I can create a BST for all sorts of data types... Int, string, so on. I've been asked to use a BST as a data structure. Let's imagine it's weather data. A measuring device records the temperature several times daily so I have a date and a time as well as the temperature. Each record I want to use a struct as a container, so I want something like this: struct Record { string DateTime; float temperature; }; DateTime is a string here because it has a format like dd/mm/yyyy xx:xx. I could convert that into an int perhaps. With thousands of records, I want to insert them all into my BST. This isn't going to work, my BST template has no idea how to compare 2 Records to say which one will go into the left link and right link. Can I just write a bool operator > function that will take 2 Records, compare the datetimes of both, then say whether a Record made later is 'greater than' a Record made earlier, thus it goes into the tree here and so on? Will this work in general? Should I do something like create a map with an int called DateTime paired with a record, then insert all the integer values representing the DateTimes into my BST. Then when I need to get back my data, first I search the BST to check whether there is an entry, then use that result against my map, which is then supposed to give me the object I want. The reason why I need to do all this is because I would like to perform calculations such as, 'give me the average temperature for each month in the year of 2018'. Then I would search my BST to give me back all my DateTimes for each month of 2018, then access my Records through the map to tally up the temperatures and average them. Please feel free to point me in the right directions. I found that googling how to create BSTs of objects and structs gave me implementations of BST using integer nodes, which is not enough...?
As trincot pointed out, there are quite a number of ways to use a binary search tree with structures. I kept in mind that I should NOT use a separate structure to store my records, as they rightly pointed out that using my BST template it should generally be declared as BST< Record > rather than BST< int >. In my earlier example I used a struct to store Record data. I decided to use a class instead. In my new Record class I added operator functions so that my BST template knew what to do when comparing 2 objects. Imagine that my new Record class looks something like this: class Record { public: /* member variables */ void printValues(); bool operator>(const Record& otherRecord) const; bool operator==(const Record& otherRecord) const; }; ostream & operator<<(ostream &out, const Record &REC); //implementation below bool Record::operator>(const Record& otherRecord) const { return (date > otherRecord.date); } bool Record::operator==(const Record& otherRecord) const { return (date == otherRecord.date); } As you can see I overloaded the > and == operators. For example in my template, functions that use these operators look like this (this is just 1 of the functions for illustration): template<class T> void BSTTemplate<T>::insert(const T& insertItem) { Node<T>* current; Node<T>* trailCurrent; Node<T>* newNode; newNode = new Node<T>; newNode->info = insertItem; newNode->leftLink = nullptr; newNode->rightLink = nullptr; if (root == nullptr) root = newNode; else { current = root; while (current != nullptr) { trailCurrent = current; if(current->info == insertItem) { cout << "Item is already in tree. Duplicates not allowed." << endl; return; } else if(current->info > insertItem) current = current->leftLink; else current = current->rightLink; } if (trailCurrent->info > insertItem) trailCurrent->leftLink = newNode; else trailCurrent->rightLink = newNode; } }// end insert() Without the overloaded operators, statements like if(current->info == insertItem) and else if(current->info > insertItem) would not work for the objects that I wish to create and use. I was advised by other users that I should type out an answer that helped me solve my problem, so there you go! Hope that helps someone else...
73,173,393
73,173,464
C++ char array compare ' ' and '\0' and counter doesn't work
I'm new to C++. I have a simple practice function I try to count how many words in a full name, first I pass a char array fullName to nameCount function with a counter then it will compare each char in the array with ' 'and '\0' if it meet any of these 2 chars, counter will +1. But I don't know why the counter give back a very large number. Please help me out with the code. Thanks a lot. #include <iostream> using namespace std; void nameCount (char[],int&); const int LENGTH =30; int main() { char name[LENGTH]; int count=0; cout<<"Input full name: "; cin.getline(name, LENGTH); nameCount(name, count); cout<<count; return 0; } void nameCount(char fullName[],int& count) { for(int i=0; i<LENGTH;i++){ if (fullName[i]==' ' || fullName[i]=='\0') count++; } } Example & Result: Input Full Name:John Smith 0
You have the common newbie confusion between parameters and return values. When you want a function to calculate something you return that value from the function, You don't pass the variable as a parameter. Here's how your code should look int nameCount(char fullName[]) { int count = 0; for (int i = 0; i < LENGTH; i++) { if (fullName[i] == ' ' || fullName[i] == '\0') count++; } return count; } and here's how you call the function int count = nameCount("John Smith"); Even with that improvement there appear to be bugs in your code. I would suggest this as an improvement int nameCount(char fullName[]) { int count = 0; for (int i = 0; fullName[i] != '\0'; i++) { if (fullName[i] == ' ') count++; } return count; } However since I can't see the rest of your code this might not be right. EDIT So full source code is now available (thanks). Here's a fully working main #include <iostream> using namespace std; int nameCount (char[]); const int LENGTH =30; int main() { char name[LENGTH]; cout<<"Input full name: "; cin.getline(name, LENGTH); cout << name_count(name) << '\n'; return 0; } And as stated your function actually counts spaces not words, so nameCount("John Smith") returns one not two, but that's a different problem.
73,173,608
73,173,675
Red-black tree in C++ STL
In current C++ STL, where are red-black tree used? (I assume map and set do?) Is the red-black tree used 2-3 tree (ie only left or right child can be red) or 2-3-4 tree (ie both left and right child can be red)? is there a red-black tree lib in STL?
std::map, std::multimap, std::set and std::multiset are often implemented in terms of red-black trees but doing so is not mandated by the standard. Since using a red-black tree is not required there is also no requirement for any particular flavor of RB tree. I believe (though am not certain) that SGI's STL (upon which much of the original standard library is based) actually does have a red-black tree available. If it helps, I know boost::intrusive does have a reusable red-black tree implementation.
73,173,609
73,173,712
C++ - Should you delete allocated memory in the copy assignment operator of a class that uses raw pointers?
I am still somewhat new at c++, and I am a little confused about this. Say we have struct struct_x that uses raw pointers as attributes. Should the raw pointers then be deleted in the copy assignment operator, when they are already allocated? Or should you just assign the new pointee to the pointer? (I am aware that it is advised to use smart/unique/shared pointers). Code example: struct struct_x { public: // Some attributes. char* m_arr nullptr; size_t* m_len = nullptr; size_t* m_alloc_len = nullptr; // Default constructor. struct_x() { m_len = new size_t(0); m_alloc_len = new size_t(0); } // Copy constructor. // Treat "struct_x" as a unique pointer for this example. struct_x(const struct_x& x) { // Assign. m_arr = new char[*x.m_alloc_len + 1]; memcpy(m_arr, x.m_arr,*x.m_len); m_len = new size_t(*x.m_len); m_alloc_len = new size_t(*x.m_alloc_len); } // Copy assignment operator. void operator =(const struct_x& x) { // // // OVER HERE // // Should the pointers be deleted when they are already allocated? // Like: if (m_arr != nullptr) { delete[] m_arr; } if (m_len != nullptr) { delete m_len; } if (m_alloc_len != nullptr) { delete m_alloc_len; } // Or not? // Assign. ... } } Second question: Do I need to delete the old m_arr after using memmove? // Resize. void resize(const len_t& req_len) { using T = char; // only for this example. if (req_len > m_alloc_len) { if (m_alloc_len == 0) { m_alloc_len = req_len; } m_alloc_len *= 16; T* l_arr = new T [m_alloc_len + 1]; memmove(l_arr, m_arr, m_len); // if (m_arr != nullptr && m_arr) { delete [] m_arr; } // Do i need to delete here, no right? m_arr = l_arr; } }
If you are implementing a string-like class as an exercise, then m_len and m_alloc_len should not be pointers at all. Only m_arr should be a pointer. If you are not doing an exercise, you should be using std::string or perhaps std::vector<char>. Having said that... It is perfectly fine and necessary to delete owning raw pointers in assignment operators of resource-managing classes. There is a caveat though. The assignment operator should be protected against self-assignment. If you do my_object = my_object; then without such protection your program will access deleted memory area. You want this: void operator =(const struct_x& x) { if (this != &x) { // contents of your assignment operator } } my_object = my_object is an unlikely assignment to appear in a program, but such things can and do happen, especially if there is indirection involved. Say when doing a[i] = a[j], it is perfectly reasonable to have i == j. There are other (better) ways to protect against self-assignment. You will encounter them in due course. You probably need to learn about move semantics first.before