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
68,751,682
68,764,542
Is a class template's name in scope for a qualified out-of-line destructor's definition?
Recent versions of clang (since clang-11) issue a warning when compiled with -pedantic for the following segment of code: namespace foo { template <int A> struct Bar { ~Bar(); }; } // namespace foo template <int A> foo::Bar<A>::~Bar(){} With the generated warning (and error with -Werror) being: <...
From what I have learned since posting the question, this warning is, strictly-speaking, correct -- though it most likely a defect in the wording of the standard. According to Richard Smith in LLVM Bug 46979: The diagnostic is correct, per the standard rules as written; strictly-speaking, the C++ rules require this d...
68,751,735
68,751,885
How can i draw a point in my QFrame, i want to use qt to do that?
I want to draw a pixel in my QFrame, i am overwriten my painEvent function like this: void MainBoard::paintEvent(QPaintEvent *event) { QFrame::paintEvent(event); QPainter painter(this); point.paintPoint(event,100,100); } and my class point have the function class Point: public QWidget { public: void pa...
You're calling QWidget::paintEvent(event) on your Point object from a context where Qt isn't expecting it -- i.e. from within MainBoard::paintEvent(QPaintEvent *). Typically in Qt you never explicitly call paintEvent() on a different widget yourself; rather Qt's event-loop code calls it for you at the appropriate time...
68,751,918
68,752,123
Why does it not allow me to input values past [1][0]?
#include<iostream> using namespace std; int main() { int row1,col1,row2,col2,a,b; int matrix1[row1][col1]; int matrix2[row2][col2]; int num; int val; cout<<"\nEnter matrix 1 dimensions in 'row column' format(example: 2 3): "; cin>>row1>>col1; cout<<"\nInput values for matrix ...
int row1,col1,row2,col2,a,b; int matrix1[row1][col1]; How big do you think these arrays are? C++ is not a "dataflow" language where you can use a variable and the runtime would pause the execution until you initialise the value later. Instead, the variable is read immediately and if the variable isn't initialised - ...
68,752,145
68,752,336
I keep getting this error "terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc" when I run my code
This error occurs in the "bfs" function of my C++ code. I'm trying to code a graph data structure but it seems like there is something that is either not initialized or not storing input as it should. Can anyone please help me with this? #include<iostream> #include<vector> #include<queue> #include<stack> using namespac...
Generally, std::bad_alloc means that Heap memory allocation failed (and that your system is out of RAM). In your case, it could be caused by too high console-input (for n, m, u or v variable). BTW, always first try to use debugger to locate exact line-of-code which caused the issue (to help people trying to answer).
68,752,542
68,752,589
How to add a parameter value when forwarding parameters to a variadic template function?
Suppose that I have two functions below, in the Foo() function, how can I pack the hw string into args and forward them to Bar()? I tried std::bind but that didn't work. template<typename T, typename... Args> void Bar(Args&&... args) { // do something with args } template<typename T, typename... Args> void Foo(Ar...
How to add hw to the forward list? Simply Bar<T>(hw, std::forward<Args>(args)...); ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ or if you want to move the hw to Bar() #include <utility> // std::move, std::forward Bar<T>(std::move(hw), std::forward<Args>(args)...); ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^...
68,752,577
68,752,889
How does std::vector in c++ gets deallocated by default
I have read that, in c++ STL's vector gets deallocated as soon as the variable goes out of scope. So I tried going through STL's vector implementation, but it doesn't seem to be happening in the destructor of class vector, so how does deallocation happen or how is it being implemented.
There are several STL implementations, they diff from each other, but they are similar. Let's take the latest version of GCC's libstdc++ as an example: The destructor of std::vector, all the elements in the vector are destroyed via calling std::_Destroy ~vector() _GLIBCXX_NOEXCEPT { std::_Destroy(this->...
68,753,073
68,754,070
Is it a data race if I enforce 'happens before' relation between conflicting expressions at runtime?
As per cppreference, When an evaluation of an expression writes to a memory location and another evaluation reads or modifies the same memory location, the expressions are said to conflict. A program that has two conflicting evaluations has a data race unless: a) both evaluations execute on the same thread or in the s...
Will the above server's code fall in the category of programs having data race? Yes. Is there a way to enforce ordering at compile time in a multi-threaded C++ program when threads are sharing data without using C++ language's synchronisation constructs(mutex/futures/atomic) etc. Implementations can provide additio...
68,753,288
68,754,556
Default for resolving ambiguous access
Consider the following classes: class VisitableNode { public: virtual void Visit(); }; class VisitableGraph { public: virtual void Visit(); }; class OtherNode { }; class OtherGraph { }; template<class G, class N> class GraphNode : public G, public N { }; class MyVisitableGraph : public GraphNode<VisitableG...
As suggested by @463035818_is_not_a_number, this answer gave a solution: template<class G, class N> class GraphNode : public G, public N { public: template<class = decltype(&G::Visit)> void Visit() { G::Visit(); } }; It loses the virtual specifier, so it might not always be usable. And it is very h...
68,754,092
68,754,602
define array of class object at time of declaration with val.Class with array in constructor initializer list & ptr members assigned with member array
This is my class #include <iostream> #include <string> class abc{ private: //int *px=x; //int *py=y; //int *pz=z; public: int x[10]; int y[10]; int z[10]; int *px=x; int *py=y; int *pz=z; abc(const int _px[],int _py[],int _pz[]):x{{10}},y{{10}},z{{10}} { } }; I want to...
With std::array, you might do class abc{ public: std::array<int, 10> x; std::array<int, 10> y; std::array<int, 10> z; abc(const std::array<int, 10>& x, const std::array<int, 10>& y, const std::array<int, 10>& z) : x{x},y{y},z{z} {} private: // Not sure why you want those members :-...
68,754,099
68,754,337
C++ factory of a class that specializes a templated superclass
I'm developing a C++ framework for mathematical optimization and I'm struggling to find a good design for my sparse matrix representations. Basically: I have two sparse matrix representations: types A and B ; I have (say) four linear solvers, Alan, Alicia, Beth and Benjamin. Alan and Alicia works exclusively with A ma...
LinearSolverAlan and LinearSolverBeth do not share a common base, because LinearSolver<MatrixTypeA> and LinearSolver<MatrixTypeB> are two unrelated types. You can use either if constexpr to discard the branches that are not used in the specific instantation of the factory or specialize the whole factory: template <type...
68,754,301
68,754,824
Mongo dB c++ driver installation issues in Windows
I was installing mongo DB C++ driver on windows using this http://mongocxx.org/ . My aim is to write mongo dB code on Qt Creator using C++. so I am a beginner so the steps given in above link not in details . if anybody did this before please describe in simple manner... edited: i was trying to build the driver file u...
You can tell CMake to generate standard makefiles instead by doing: cmake -G "Unix Makefiles" -DENABLE_AUTOMATIC_INIT_AND_CLEANUP=OFF .. Alternatively, you can just install Ninja (and make it available on your $PATH), which is the better choice for a CMake target. Check cmake --help to see which generators are availab...
68,754,542
68,754,759
Why does std::is_same always give me a compiling error
In my project, there are some config files. I need to extract them either as integers or as strings. To do so, I write a function as below: template<typename T> void loadTxtConfig(const std::string& filename, std::set<T>& ids) { std::ifstream infile(filename); if (!infile) { return; } std::strin...
In C++11 I suggest that you break out the parameter specific part (the conversion) and use SFINAE (substitution failure is not an error) to make use of the correct one: #include <type_traits> template<typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0> T convert(const std::string& line) { ...
68,755,051
68,755,239
I don't understand the process converting string to int
Given the following code. this problem is Leet Code 415. string addStrings(string num1, string num2) { string res; int sum = 0; int i = num1.size() - 1; int j = num2.size() - 1; while(i >= 0 && j >= 0) { sum += (num1[i--] - '0') + (n...
In c++ characters can be implicitly cast to integers using their ASCII codes. I don't really want to spoil the fun of solving the given problem so i'll just provide a hint here: Given a single digit number '2' and '4' with an ASCII code of 50 and 52 (decimal) respectively, subtracting '0' with an ASCII code of 48 from ...
68,755,199
68,755,417
Infinity while loop C++ char
From this C++ code here I try to create an array of char to test either the input is valid or not, as it should be starting with 3 letters with remaining 4 numbers (ex. ABC1234). function to test number bool testNum(char custNum[], int size) { // test first 3 characters for alphabetic letters for (int i = 0; i ...
When the input line is too long, getline sets the failbit of cin, causing each future read from cin to yield an empty string.
68,755,298
68,755,436
Implement pure virtual function with using
Consider the following program class Node { public: virtual void Visit() = 0; }; class Graph { public: virtual void Visit(); }; class GraphNode1 : public Node, Graph { }; class GraphNode2 : public Node, Graph { using Graph::Visit; }; class GraphNode3 : public Node, Graph { public: virtual void Visit() {...
Node and Graph are unrelated classes. Which makes Node::Visit and Graph::Visit distinct unrelated member functions. Neither can override the other. You seem to think Graph::Visit is somehow "better" than Node::Visit on account of not being pure virtual, and should therefore override it. But there is no objective reason...
68,755,676
68,756,147
Read Numbers from txt file with C++
So in my text "123456789#987654321" is written. And in C++ i got 2 int called numbers1 and numbers2. I want numbers1 to be 123456789 and numbers2 will be 987654321. Could you please tell me how can i do that?
You can try the code below. #include <iostream> #include <fstream> #include <string> #include <vector> using namespace std; int main() { cout << "Hello, World!" << endl; ifstream in_file; in_file.open("your_text.txt"); if (!in_file.is_open()) { fprintf(stderr, "Unable to open file!\n"); ...
68,756,225
68,757,571
Calculate font "size" in DIPs of a system font
I have few BS_OWNERDRAWN buttons and using Direct2D and Direct Write to draw them. I also need to draw button text within button rectangle, for this I use IDWriteTextFormat which requires to specify "font size" in DIPs (device independent pixels). I want font size in those buttons to be of same size as other non owner ...
I figured out to calculate font size of other common controls to be used for IDWriteTextFormat the formula is simple: float CustomControl::CalculateFontSize() { const long units = GetDialogBaseUnits(); const DWORD height = HIWORD(units); return static_cast<float>(height); } Only problem with this is if yo...
68,757,025
68,757,064
windows uses long int as if in a 32-bit machine while in 64-bit
I'm using 10 64-bit. when running the following code for example, I get an overflow and a negative number is printed, while on a linux 64-machine I get the actual number printed: #include <stdio.h> int main() { long int a = 3845354610; printf("Hello, World!%ld\n", a); scanf("%ld", &a); return 0; } The...
How can this be fixed? By using long long or std::int64_t. long is required / guaranteed to be at least 32 bits, and that's the size of long on (64 bit) windows.
68,758,398
68,763,566
Problem with converting vector of string to vector of doubles
I am trying to write a program that reads some numerical values from a .csv file, stores them in a std::vector<std::string>, and then converts these values into doubles and stores them in a std::vector<double>. I am trying to do the conversion using stringstreams, which has worked fine for me in the past. I have manage...
You should be reading individual lines from the file first, and then splitting up each line on commas. And there are easier ways to handle the rest of your code, too. Try something more like this instead: #include <string> #include <fstream> #include <iostream> #include <sstream> #include <vector> int main() { st...
68,758,443
68,764,649
Can't check if a table exist in QT MYSQL
I'm trying to check if a table exist in a schema for QMYSQL inside QT framework. I have connected the MySQL server and it can create a table, but NOT check if a table exist. This is the code for checking if a table exist query.exec("CREATE TABLE " + table_name + "(ID BIGINT PRIMARY KEY)"); QStringList tables = this->qS...
try this line: query.exec("CREATE TABLE " + table_name + " (ID BIGINT, PRIMARY KEY (ID));");
68,758,624
68,758,781
Why do tuples not get unused variable warnings?
In the following example, compiling with -Wall, some of the unused variables are not warned about: #include <tuple> struct Foo { int a, b; }; struct Bar { ~Bar() {} int a, b; }; int three() { return 3; } int main() { Foo f0 {1, 2}; Foo f1 {three(), 2}; Bar b0 {1, 2}; Bar b1 {three(), 2}...
The compiler will do its best to flag unused variables, but this is difficult for non-trivial types, and both Bar and std::tuple<int, int> are non-trivial. static_assert(std::is_trivial_v<Foo>); static_assert(!std::is_trivial_v<Bar>); static_assert(!std::is_trivial_v<std::tuple<int, int>>); As is described in Bug 552...
68,758,698
68,758,774
How unique() function for array works
int a[4] = {3,1,2,3}; sort(a,a+n); int j = unique(a,a+n) - a; // j=3 In this code variable j returns total numbers of unique element in the array a. But I couldn't understand how this code is working. I know that in lists, list::unique() is an inbuilt function in C++ STL which removes all duplicate consecutive element...
std::unique() is going to move the duplicates in the range [a+0, a+n), and it returns a new iterator in that range that will mark the new "end" of the array, i.e, where the first non-unique item is now moved to in the array. If you then subtract from that iterator the beginning iterator, which you do with unique(a,a+n)...
68,759,142
68,759,202
delete c in void insert() prints infinite numbers, if I comment it out I get correct output
This program creates and prints a link list in cpp When this program runs an infinite no. of numbers start printing in the console #include <cstdlib> #include <iostream> using namespace std; class Node { public: int data; Node* next; }; class Node* head = NULL; int length = 0; In this function if...
In your insert function, the loop condition is c->next != NULL. Therefore c points at an in-use node after the loop, and delete c; destroys the node and cause trouble. In other hand, the loop condition in your print function is c != NULL. Therefore c will be NULL after the loop and delete c; won't cause trouble because...
68,759,234
68,759,389
how to compare variables of one class object with another class's object?
Say I have two classes: player and item the player has several class variables, including int strengthPoints, dexterityPoints, constitutionPoints, intelligencePoints, wisdomPoints, charismaPoints; and the item has a variables int requiredStrengthPoints, requiredDexterityPoints, requiredConstitutionPoints, requiredIntel...
I would encapsulate those values into a Stats struct like struct Stats { int strength; int dexterity; int constitution; int intelligence; int wisdom; int charisma; }; then your Player can have a Stats indicating their current levels, and the Item can have a Stats indicating required minimum str...
68,759,567
68,761,324
static inline associative collection included in 2 gtest files throws read access violation
I have a very simple class with a static inline member variable that is throwing "read access violation" if it's included in more than 1 test file. The error is thrown in the destructor after all tests pass. It also only occurs in debug builds. I suspect it's trying to delete the member variable more than once. Note th...
Your analysis about double-calling the destructor is probably right. It does not happen with vectors and arrays because their own destructors are trivial, and it does not happen in release builds because the compiler optimizes out the construction and destruction of an unused object. It looks like you've discovered an ...
68,759,827
68,760,100
Incompatibility using std::string::assign from boost::array Vs std::array
Some legacy code looks like: #include <boost/array.hpp> boost::array<wchar_t, 1000> data; void func(std::wstring &str) { str.assign(data.begin()); } I am updating code to use std equivalents to boost as we update to C++17, and I thought array was a direct replacement, but when I try this I get a compile error: #inc...
boost::array<wchar_t, N>::iterator is defined as an wchar_t * std::array<wchar_t, N>::iterator is not required to be a wchar_t *. That's why your code fails to compile. It assumes that the iterators are pointers. Besides that, the code you have is problematic because str.assign(_pointer_) assumes that the pointer poin...
68,760,101
68,760,683
Why some C++ feature test macros require header inclusion?
Some C++ feature test macros( e.g. __cpp_lib_three_way_comparison ) require header inclusion(e.g. <compare>) to test for them. This seems very backwards, e.g. maybe I want to include header only when I know it is supported by compiler(more precisely compiler+std lib impl it uses), e.g. let's say I have my_fancy_string_...
Following on from the comments, an issue to touch on here is that you don't want the compiler to have to know exactly which features are and are not supported by the library implementation(s) it uses. To do so would require changes to the compiler every time the library is updated, and that would quickly become unmanag...
68,760,490
68,760,544
Can trivial integral const variables always be used as template values?
This question is similar to this one, but more specific to pre-c++11 scenarios. I've noticed with Clang and g++ that the following compiles and works fine with pre-c++11: enum En { V0 = 0 }; template <int SZ> class C { }; template <En EN> class E { }; int main() { const int SIZE = 42; C<SIZE> c; const int...
So is this guaranteed to work Yes. From [expr.const]/1 in N1905 (which is C++03-ish standard release): 5.19 Constant expressions [expr.const] /1 In several places, C++ requires expressions that evaluate to an integral or enumeration constant: as array bounds (8.3.4, 5.3.4), as case expressions (6.4.2), as bit-field ...
68,761,022
68,766,128
reflection TS - in C++23?
Reflection TS - C++ feature described here: https://en.cppreference.com/w/cpp/keyword/reflexpr I am looking for any information about this feature. I have this table describing compiler support: https://en.cppreference.com/w/cpp/compiler_support but I don't see that this feature is planned or maybe the name of this fea...
While the Reflection TS was officially finished and published, at the same time significant progress was being made developing an alternative syntax that made use of newer language features like consteval to express reflection information as values rather than types (as in traditional template metaprogramming). The TS...
68,761,048
68,761,596
Efficient check that two floating point values have distinct signs
I need to find whether two finite floating point values A and B have different signs or one of them is zero. In many code examples I see the test as follows: if ( (A <= 0 && B >= 0) || (A >= 0 && B <= 0) ) It works fine but looks inefficient to me since many conditions are verified here and each condition branch is a ...
Efficient check that two floating point values have distinct signs if ( A * B <= 0 ) fails to distinguish the sign when A or B are of the set -0.0, +0.0. Consider signbit() if (signbit(A) == signbit(B)) { ; // same sign } else { ; // distinct signs } Trust the compiler to form efficient code - or use a better c...
68,762,326
68,762,911
Format': is not a member of 'CStatic' Timers
void CTimersDlg::OnTimer(UINT_PTR nIDEvent) { // TODO: Add your message handler code here and/or call default CTime curTime = CTime::GetCurrentTime(); m_sTime.Format("%d:%d:%d",curTime.GetHour(),curTime.GetMinute(),curTime.GetSecond()); // Update the dialog UpdateData(FALSE); CDialogEx::On...
With MFC, you can create two kinds of variables associated with a STATIC: control with a type of CStatic (as you have) and value with a type of CString. You tagged visual-studio-code - is that what you are using? If you are using Visual Studio, I suggest to use a wizard: right-click on your STATIC control in the dialog...
68,762,824
68,762,972
SPDLOG_LOGGER_CALL and __VA_ARGS__ in
I'm trying to understand why my variadic arguments don't work in spdlog. I understand that there is an SPDLOG_LOGGER_INFO macro to do what I do, but at the moment I need to understand how SPDLOG_LOGGER_CALL works. So here is the code: #include <iostream> #include <spdlog/sinks/syslog_sink.h> #include <spdlog/spdlog.h> ...
SPDLOG_LOGGER_CALL() is just a wrapper for spdlog::logger::log(), which does not use printf-style format strings, like you are expecting. If you read spdlog's documentation, you will see that spdlog uses the {fmt} library internally: Feature rich formatting, using the excellent fmt library. Which has its own syntax ...
68,762,987
68,763,220
Is there way to actually move allocated object to std::list
In C styled linked list you just set pointer to allocated object, while in C++ copy seems unavoidable. Naive test code: #include <cstring> #include <iostream> #include <chrono> #include <memory> #include <list> #include <vector> using std::cout; struct LinkedS{ LinkedS *next = nullptr; float f; std::vector...
This usage of new is not a good C++, it is not Java/C#, do not use new unless you have to and when you have to, use std::unique_ptr. Are you looking for emplace_front, emplace_back? They can construct the stored object at its final destination. C++20 #include <list> #include <vector> struct S{ float f; std::vec...
68,763,023
68,764,580
Apparently erroneous initialization of class template member compiles just fine
Consider the following MCVE code: struct Id { static inline int id(int c) {return c;} }; template <class C> class Foo { C m_bar; public: Foo() = default; Foo(int) : m_bar{bar} {} // Fails in clang, compiles in gcc/msvc Foo(int, int) : m_bar(bar) {} // Compiles with all gcc/clang/msvc Foo(int, int, ...
Class template members are instantiated on-demand. See [temp.inst]/9: An implementation shall not implicitly instantiate a function template, a variable template, a member template, a non-virtual member function, a member class, a static data member of a class template, or a substatement of a constexpr if statement, u...
68,763,574
68,820,960
Bjam how to print include path used in compiling
I have a Jamroot.jam for a big project. I want to print all paths where g++ searches for includes when compiling, how can i do this (normally -v flag in g++) ? I try bjam --debug-configuration but it doesn't do what i ask
Found answer here: How to build Boost with C++0x support? To compile using clang, use the cxxflags and linkflags: ./bjam \ ... cxxflags="-std=c++0x -stdlib=libc++" \ linkflags="-stdlib=libc++" \ ... Passing a -v to cxxflags is also helpful when debugging.
68,763,935
68,764,391
How can I use a constructor (explicit) to convert a int type to a class?
I must create a code that uses an explicit constructor to convert a int type to an existing class. class MyClass {public: MyClass(int& obj); //I tried to use a syntax similar to a copy construct } int a; MyClass a();
class MyClass { private: int m_value; public: explicit MyClass(int value) : m_value(value) {} }; int a = ...; MyClass obj(a);
68,764,785
68,774,355
Visual Studio 2019 Cannot include existing folder (not visible with show all files)
What I'm trying to do I'm currently attempting to include a set of folders and the files inside in an unreal engine 5 project. I'm working out of Visual Studio 2019 Community and adding Photon Engine into my game source. What is shown in the solution, and what is in the folder. However, every example of adding this fo...
Visual Studio in general: First, you should deactivate the 'Show all files'-option. Otherwise you will see absolutely every file that is located inside the solution and project folders on disk. Then the trick is to not add a "folder" (which isn't possible), but a "filter" (which is like a folder, except for not necessa...
68,765,004
68,768,697
convert octave Matrix to cv::Mat in oct file
I wrote a simple Oct file to wrap an OpenCV function. This is my code:- #include <octave/oct.h> #include <opencv2/imgproc.hpp> DEFUN_DLD (cornerHarris, args, , "Harris Corner Detector") { // Processing arguments if(args.length()<4){ print_usage(); } Matrix octInMat = args(0).matrix_value(); int blockS...
I figured it out by commenting line by line in my code. The issue was occurred from this line because of a type casting issue. cvInMat.at<int>(r,s) = octInMat(r,s); I changed this as following. cvInMat.at<uchar>(r,s) = (uchar)octInMat(r,s); This answer helped me to fix it.
68,765,617
68,765,811
Inserting pointer to elements from a list into a map results in garbarge values
I was trying to implement Prim's algorithm(eager) which requires to keep a track of best incoming edge(least cost) to a vertex. For this I use stl map as: std::map<int, Edge*> bestEdgeFor; However when I try to assign an edge to some key, what is actually stored is an edge with garbage values for the data members. As ...
This is the Graph class and I am doing the assignment operation in a member function of this class. e comes from the adjList. Is the scope valid? Normally, yes. This is because objects in linked list have stable address. As long as they are in the list, you can take their addresses and put the pointer in a map withou...
68,765,660
68,776,775
What is the proper way to optionally compile a library with a build flag (to place in `target_compatible_with`)?
Suppose I have a library implementation that I only want to compile when the user specifies it at build time. Should I use the features flag? If so, how could I use the features flag to constrain compilation like you can with target_compatible_with in cc_library, cc_test, and cc_binary? If not, what is the best way to ...
Sounds like you want a user-defined build setting that is a command-line flag. The easiest way is to use one of the common build settings rules, and instantiate it in a BUILD file (call it flags/BUILD for this example): load("@bazel_skylib//rules:common_settings.bzl", "bool_flag") bool_flag( name = "flag", buil...
68,766,082
68,797,119
C++: What is the output, if no optimizations are applied to these different ways to create/initialize, copy, assign?
I found a bit of confusion in the ways a variable is constructed, copied, assigned because in the compilers I tried they usually apply some kind of optimization (remove temporary etc.). I'm listing the different ways I tried and the output of my program in comments below. May be some of them included temporary object c...
Using explicit to ctor and copy ctor and deleting each of the functions, I was able to get below results. //constructor type c(8); //explicit ctor type c2{8}; //explicit ctor type c3 = 8; //implicit ctor, explicit copy type c4 = {8}; //implicit ctor type c5 = type(8); //explicit ctor, impli...
68,766,353
68,766,573
Does the following pointer usage lead to undefined behavior?
(I can't think of a more specific Title for my question, so it's currently generally stated) Consider the following snippet struct trie_node { trie_node() : children(26) {}; std::vector<std::shared_ptr<trie_node>> children; }; int main() { auto root = std::make_shared<trie_node>(); root->children[0] = ...
When you do *c2 = nullptr, you destroy the object root->children[0]. This in turn destroys the object root->children[0]->children[1], since you've destroyed its parent. That means you have a reference to an object that no longer exists, and reading its value has undefined behavior, which means 0x37 is a perfectly vali...
68,766,845
68,767,331
Better way to print from the user inputted in rows and columns? Without for loops? Recursion?
I have been trying to search if there are other ways to print the below pattern: Print a solid Rectange #### #### #### I used the below code: using namespace std; int main () { int r,c; cout<<"Enter the number of rows and then columns:\n"; cin>>r>>c; cout<<"Pattern:\n"; for(int i=1; i<=r; i++) ...
Normally recursion involves the use of individual stack frames, which atomize the process of each function call without stepping on the previous function call. There are problem sets where recursion is the best case solution to your problem, Ackermann function and complex mathematic functions coming to mind, however in...
68,767,307
68,767,436
"Type Name is not allowed" issue
So I'm trying to make a header file for math to implement in my game engine. I declared a struct and a function to simply return the struct. typedef struct { double x, y; } Vector2D; static inline Vector2D vector2D (double x, double y) { return (Vector2D) {x, y}; } I am using Visual Studio 2010 and it it sho...
What can possibly go wrong? You are trying cast {x, y} to a Vector2D here: return (Vector2D) {x, y}; Is there any way to fix it? Since you are using Visual Studio 2010 I'm assuming that you are using a C++ standard prior to C++11. Here's how it could be done in C++98 or C++03: #include <iostream> struct Vector2D ...
68,767,675
68,767,700
How to solve linker errors?
I am getting the errors like so LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ) LNK1120 1 unresolved externals I am not using any strange libraries, it is very simple: #include <iostream> using namespace std; class myClass { int* iP; float f ...
I think you accidentally put the main function inside your class scope. try moving the last }; above your int main line
68,767,685
68,767,706
About iterator of containers
I do not know, why does it output 1024? vector<int> default_container = { 1,2,3,4,5,6,7,78,8,1024 }; cout << *default_container.end() << endl; // 0 default_container.pop_back(); for (auto it : default_container) { cout << it << ","; } cout << endl; cout << *default_container.end() << endl; // 1024 why?why?why?...
Your program has Undefined behavior! You are de-referencing the end iterator, at the lines cout << *default_container.end() << endl; ... cout << *default_container.end() << endl; which gives you undefined behavior. Form cppreference.com the std::vector::end, std::vector::cend Returns an iterator to the element foll...
68,767,756
68,767,846
Display Array User Input from Function
This is my code at the moment. It is a lottery game and I get user input for 7 numbers and do not allow duplicates (same goes with the random generated). I need to display the user's numbers and the winning random numbers at the end of the main next to LOTTO RESULTS and WINNING NUMBERS. #include <iostream> #include <ct...
It seems you might be new to programming so here you go, your working program: #include <iostream> #include <ctime> #include <cstdlib> #include <string> using namespace std; void getLottoPicks(int userNums[], int size); void genWinNums(int winNums[], int size); int main() { const int size = 7; int UserTicket...
68,769,119
68,982,089
How to build a graph of specific function calls?
I have a project where I want to dynamically build a graph of specific function calls. For example if I have 2 template classes, A and B, where A have a tracked method (saved as graph node) and B has 3 methods (non-tracked method, tracked method and a tracked method which calls A's tracked method), then I want to be ab...
In general, you have 2 strategies: Instrument your application with some sort of logging/tracing framework, and then try to replicate some sort of tracing mixin-like functionality to apply global/local tracing depending on which parts of code you apply the mixins. Recompile your code with some sort of tracing instrum...
68,769,372
68,769,629
C++: cannot convert argument 2 from 'int' to 'const Vector &'
im kinda new to c++ and i just can't figure it out on how to fix the problem the intelisense error i get is no suitable constructor exists to convert from "int" to "Vector" here is an snippet of code Vector vTargetPos = GetEnemyLKP(); vTargetPos.z = GetFloorZ(vTargetPos); if (GetNavigator(...
if (GetNavigator()->SetRadialGoal(vTargetPos, random->RandomInt(50, 500), 23, 90, 175, m_bLoopClockwise)) Random function type is int but second reference of SetRadialGoal function is const Vector&. Compiler can't convert int to Vector because there is no constructor for that. So, you should create a constructor for c...
68,769,618
68,769,702
Why do I need to move `std::unique_ptr`
Given the following code: #include <iostream> #include <memory> struct A {}; struct B : public A {}; std::pair<bool, std::unique_ptr<B>> GetBoolAndB() { return { true, std::make_unique<B>() }; } std::unique_ptr<A> GetA1() { auto[a, b] = GetBoolAndB(); return b; } std::unique_ptr<A> GetA2() { auto [...
I don't understand why I need to call std::move to make the function work. Because the corresponding constructor of std::unique_ptr has a parameter of rvalue reference type: template< class U, class E > unique_ptr( unique_ptr<U, E>&& u ) noexcept; See documentation for details: https://en.cppreference.com/w/cpp/memo...
68,770,136
68,771,705
Returning const reference parameter without copying
I want to return a heavy object which I pass as a const reference without copying. The code looks something like this: #include <iostream> class heavy_obj { public: heavy_obj() { std::cout << "Standard" << std::endl; } heavy_obj(const heavy_obj&) { std::cout << "Cop...
You can't move from a const value, so the function can't take by const &. You could do this, so the caller has to supply an rvalue, either moving or explicitly copying lvalues they wish to pass. heavy_obj return_obj_or_default(heavy_obj&& t, bool ret) { if(ret) { return std::move(t); } else { re...
68,770,171
68,770,535
Member function for typedef
I am wondering if the following is possible in C++. I have a typedef template<typename T> struct wrapper {}; using vecint = wrapper<std::vector<int>>; and I want to write a function size for which I can use member function syntax. I.e. write vecint v{1,3}; v.size(); instead of vecint v{1,3}; size(v); Why I want to d...
A possible way would be to wrap struct wrapper in a new class where you would add the relevant methods: template<typename T> class my_wrapper: public wrapper { public: using wrapper; // import parent ctors int size { return ::size(*this); } }; using vecint = my_wrapper<std::vector<int>>; The...
68,770,240
68,770,326
Float epsilon is different in c++ than c#
So small question, I've been looking into moving part of my C# code to C++ for performance reasons. Now when I look at my float.Epsilon in C# its value is different from my C++ value. In C# the value, as described by microsoft is 1.401298E-45. In C++ the value, as described by cppreferences is 1.19209e-07; How can it b...
The second value you quoted is the machine epsilon for IEEE binary32 values. The first value you quoted is NOT the machine epsilon. From the documentation you linked: The value of the Epsilon property is not equivalent to machine epsilon, which represents the upper bound of the relative error due to rounding in floati...
68,770,733
68,777,999
gdb single stepping until exit from function
I'm working on a project which have following architecture. sync |--- CMakeLists.txt |--- SyncManager |--- CMakeLists.txt |--- src |--- SyncCommon |--- CMakeLists.txt |--- src |--- SyncProcessor |--- CMakeLists.txt |--- src Both SyncManage...
Your sync/SyncCommon/CMakeLists.txt has this: set(CMAKE_CXX_FLAGS " -g -Wall -O2 -w -fpermissive -pthread") Your sync/SyncManager/CMakeLists.txt has this: set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g -O0") file(GLOB project_SRCS src/*.cpp src/*.h) You are using C flags, despite having C++ sources. You should set both CMAKE...
68,771,371
69,537,163
PyTorch to onnx and use with opencv-dnn?
I want to run yolov5 with opencv dnn in C++, for this, I have converted PyTorch model to onnx, from this link But that onnx is not working with opencv dnn module. Anyhelp would be appreciated.
I have followed below links and have successfully run yolov5 with C++ Link-1 Link-2
68,771,383
68,773,338
a problem with the raylib installation on linux
im using Peppermint 10 an ubuntu based distro so i did the following commands here and everything went well until this (the input) cmake -DBUILD_SHARED_LIBS=ON .. (the output) -- Testing if -Werror=pointer-arith can be used -- compiles -- Testing if -Werror=implicit-function-declaration can be used -- compiles --...
Do this: sudo apt install g++ sudo apt install cmake (should be in version 3.11 or higher) download to your project folder ex. 'new-game' folder those three files from https://github.com/RobLoach/raylib-cpp/tree/master/projects/CMake (main.cpp, README.md, CMakeLists.txt) then cd new-game && mkdir build && cd build && ...
68,771,497
68,771,704
identifier "ParseNetworkString" is undefined although I included the header files
MSVC keeps telling me that ParseNetworkString is undefined. But I've done: #include <Winsock2.h> #include <Ws2tcpip.h> #include <iphlpapi.h> as expressed in the remark part of the docs Thank you.
I've had a look inside "iphlapi.h" and it states (line 1287) // app must include winsock2.h, ws2ipdef.h, and windns.h to use this API So when I use #include <WinSock2.h> #include <ws2ipdef.h> #include <WinDNS.h> #include <iphlpapi.h> ParseNetworkString becomes available. So it seems you were on the right track, just m...
68,771,539
68,772,015
Is It possible to call methods from a subclass from a base class type?
Hello everyone and thanks for reading, I'm new to working with classes and I've ran into an issues with making array's of objects, I have a base class, and an array of the same type, I'd like to know if it's a possibility to make subclasses of the base class type and put them into an array and call methods that're not ...
You can always have more than one pointer (or reference) to the same object. int main() { BaseClass* ObjectList[10]; SubClass TheSubclass; ObjectList[0] = &TheSubclass; ObjectList[0]->Load(10); // presumably in a loop TheSubclass.OtherFunction(); return 0; }
68,771,635
68,772,097
Incomplete type error while using class from my own dll
One more day, one more dumb question on stackoverflow, please excuse me. The idea was to make dll and then import it to another project to use it there, but after including dll header file in second project and writing paths to the .lib and header files I still have these errors: E0070 incomplete type is not allowed ...
In C++ (prior to modules) the header file needs to expose enough information about a class for another cpp file to create the object or use the type. You have just forward declared it, which is enough to make pointers or references to the type and nothing else. These errors have nothing to do with linking or DLLs or ex...
68,771,692
68,775,568
Setting both read() and send() timeouts for the same C socket on linux
I managed to set a read timeout for a C socket with: struct timeval tv_read; tv_read.tv_sec = 2; tv_read.tv_usec = 0; setsockopt(my_socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv_read, sizeof tv_read); Now, I want to make this same socket timeouts for send operations. I have found in setsockopt that the proper way ...
setsockopt() sets 1 specific option at a time. It is perfectly fine to set multiple options individually.
68,772,236
68,772,237
What is the difference between std::__gcd and std::gcd?
Many websites and questions on Stack Overflow reference a function named std::__gcd. What’s the difference between this function and std::gcd?
I did some sleuthing on this. It looks like the __gcd function is a private helper function defined in the libstdc++ implementation of the <algorithm> header (line 1503). It’s used internally only by the std::rotate function (line 1610). It was (probably) never intended to be used directly outside of the library implem...
68,772,353
68,772,414
How to filter out elements of certain data types in a vector of std::variant?
I have a std::vector of std::variant elements with type int or std::set<int>. I want to loop over this vector and insert an extra item if the iterated element is of type std::set<int>. However, it seems that querying the index at run-time is not allowed. How can I achieve this? #include <variant> #include <set> #includ...
There's nothing wrong with calling index() at runtime, this happens all the time. The real problem is: var_vec[i].insert(888); var_vec[i] is a std::variant. It does not have a method called insert(). std::get<1>(var_vec[i]).insert(888); This gives you the variant's set, which will happily allow you to insert() someth...
68,772,487
68,772,692
How to limit the scope of a "using namespace ..."? c++
I have file with "my namespace"'s (myns::) methods implementations, there are lots of "myns::" before functions. I want to write using namespace, but it will be visible in other files. I can't write "static" before "using namespace mysp;". my_namespace_file.h: namespace myns { void F1(); void F2(); } my_imp_file.h...
Simple as this: #include "my_namespace_file.h" namespace myns { void A::F1() {} // class name must be repeated, because you cannot open namespace of the class void A::F2() {} } Since you should never #include file with implementations, you can use using namespace myns; as well, but that may backfire if you will ev...
68,772,564
68,772,612
Random outputs on a program that checks if a number is perfect
I'm trying to make a program that checks if the numbers inside an array are perfect numbers. The program kinda works. It correctly checks and outputs if the numbers in the array are perfect. But there is one problem that I don't understand at all. The program checks and outputs a seemingly random amount of random numbe...
sizeof(numbers) returns the number of bytes of the array numbers. You should divide that with the size of one element like sizeof(numbers) / sizeof(*numbers) to obtain the number of elements.
68,772,986
68,773,074
How can I prevent caller to my function from using the same pass-by-reference variable in C++?
I have a legacy interface that has a function with a signature that looks like the following: int provide_values(int &x, int &y) x and y are considered output parameters in this function. Note: I'm aware of the drawbacks of using output parameters and that there are better design choices for such an interface. I'm n...
No, there's not. Keep in mind that the calling code could derive x and y from references returned from some arbitrary black-box functions. But even otherwise, it is provably impossible (by the Incompleteness Theorem) for the compiler to robustly determine whether they point to the same object, since what objects they a...
68,773,605
69,020,090
What is the end of the road for a WM_LBUTTONUP or WM_LBUTTONDOWN in a low level procedure hook?
I'm writing a low level mouse hook in Windows using the Win32 API, I want to intercept either a button being pressed down or up (still undecided) depending on certain conditions. To position ourselves let's consider the following snipped of a procedure to handle those hooks: LRESULT CALLBACK mouseHookProc(int nCode, WP...
I'm going to compile the comments in an answer so those arriving here have a clear view. @Vlad Feinstein is in the right, one shouldn't mess with the messages in the hook procedure. With @Phil1970 giving the most accurate answer one could give to the question, because each application handles messages in their own way,...
68,773,932
68,773,990
whenever I run my c++ programm, my program has stopped working
I am very new in data structures and algorithm. I get stuck in my program. I could not find the reason why it happens. whenever I run, a display pop-up and show file.exe has stopped working. If you guys know the problem, please help me. And, if I have mistaken somewhere in writing, please ignore it. Because, English is...
The member m_items is not initialized. Calling list.Insert(0, 1); will make it execute delete [] OldArray; with an uninitialized value. Add a constructor to initialize the members like: List() : m_count(0), m_items(nullptr) {} Also you should follow The Rule of Three. In other words, you should also define a copy cons...
68,774,148
68,775,160
Convert lat, long to x, y on Mollweide
I have tried to follow the instructions here but I get wild results compared to this site. Here is my code. #include <cmath> double solveNR(double latitude, double epsilon) { if (abs(latitude) == M_PI / 2) { return latitude; } double theta = latitude; while (true) { double nextTheta = theta - (2 * the...
In your solveNR() function why do you use double nextTheta = theta - (2 * theta * std::sin(2 * theta) - PI * std::sin(latitude)) / (2 + 2 * std::cos(2 * theta)); instead double nextTheta = theta - (2 * theta + std::sin(2 * theta) - PI * std::sin(latitude)) / (2 + 2 * std::cos(2 * theta)); Seems like you should use ...
68,774,328
68,774,980
File creation fails because i cant add the name
I have created a c++ program that will make a text file on the desktop of the user. My only problem is, that I need to add the name of the file. In this case, I tried to add it in the string seen below named "filename". I know that the error is that I cant use the operator "+" in the string to add the name of the file....
thx to @molbdnilo In the comments, I fixed the issue. #include <iostream> #include <string> #include <windows.h> #include <fstream> #include <sstream> #include <ShlObj.h> using namespace std; wstring GetUserDesktopPath() { PWSTR path = NULL; HRESULT result = SHGetKnownFol...
68,774,638
68,775,103
std::enable_if with multiple or-conditions
I am struggling to find the correct syntax for allowing multiple OR'ed std::enable_if conditions for my template functions. #include <type_traits> template <typename T> using Foo = std::enable_if_t<std::is_same_v<T, int>>; template <typename T> using Bar = std::enable_if_t<std::is_same_v<T, float>>; // Fine - accept...
You are trying to use enable_if_t inside of enable_if_t, which is not what you need. You need to use is_same_v inside of 1 enable_if_t, eg: template <typename T, typename = std::enable_if_t<std::is_same_v<T,float> || std::is_same_v<T,int>>> So adjust your using statements accordingly, eg: #include <type_tra...
68,774,821
68,774,893
c++ Partial template specialization with typename as void
I am writing something about Partial template specialization.What I want to do is that using a template is_valid to check if the class has a member type named valid. The source code is as below. #include <iostream> class A { public: typedef void valid; }; class B { public: typedef int valid; }; class C { }; ...
For is_valid<B>, the primary template is found, since the 2nd template argument is not specified, the default value void is used, the instantiation is supposed to be is_valid<B, void>. Then specializations get checked. The problem is B::valid is of type int, the instantiation got from specialization would be is_valid<B...
68,775,355
68,775,708
In CUDA kernel template function, how to test types?
I have a CUDA kernel template function like this: template <typename scalar_t, typename accscalar_t, typename index_type, int indexing_kind> __global__ void lstm_cell_forward( TensorInfo<scalar_t, index_type> input, TensorInfo<scalar_t, index_type> hidden, TensorI...
So my question is how to write the comparison of scalar_t to check if it equals to float? I believe you can use features of libcu++ (type traits) for this: $ cat t1868.cu #include <cuda/std/type_traits> #include <cstdio> template <typename T> __global__ void k(T val){ if (::cuda::std::is_same_v<T, float>) printf("v...
68,775,374
68,775,522
Parameter pack expansion for variadic class member (tuple or other)
I am trying to store a tuple of references in a class (via a variadic template), and then I want to "loop" over them and assign them values. Function process2 below works as expected, but I want to make function process1 work the same (making use of the stored references of the class itself). However, I can't make proc...
You're on the right track with std::apply but the syntax is incorrect; the pack expansion needs to be outside the call to process_arg. Also, you don't need the variable success at all; you can use a fold-expression directly: bool process1() const { return std::apply([](auto &&... v) { return (process_arg(v) && .....
68,776,794
68,776,878
Unable to return pointer to array C++ visual studio
I am brand new to C++ and am struggling with the idea of using arrays and returning pointers. I have a class Student in a .h file: class Student { public: // stuff int* GetNumDaysPerCourse() const; // stuff private: //stuff int numDaysPerCourse[3]; // stuff }; A...
When I try to compile this code, I get this error: error: invalid conversion from ‘const int*’ to ‘int*’ This is because GetNumDaysPerCourse() is const-qualified, so its this pointer is pointing at a const Student object, and thus its numDaysPerCourse member is treated as const data. You can't assign the address of ...
68,776,874
68,777,163
Is it possible to use C++ macros to generate blocks of code?
I have a C++ program where a certain pattern of blocks of code keeps repeating, and I am wondering if I can use C++ MACROS for the preprocessor to auto-generate this code. To be more precise I have blocks of code which look something like this: for(std::size_t i=0;i< lc_.size(); i++) { std::string str; state::MsDat...
Don't do that. template<class Z, class X, class F> void do_stuff( X&& x, F&& f ) { for(std::size_t i=0;i< x.size(); i++) { std::string str; auto tmp = f(i); convert<Z>(tmp.data(), str); x[i] = Z(str); } } write a template. We can use it like this: do_stuff<data::ClassForMMOP>( mmop_, [&](std...
68,777,758
68,777,824
C++ Comparing Array Values in Lottery Game
I'm making a lottery program and I'm trying to make a function to check how many of the user's numbers are the same as the winning numbers and write out the different rewards for having the same numbers. The code compiles just fine. I am just having the issue of creating the function and what to do in it. Basically, c...
You should do 2 loops, like this: int checkNums(int userNums[], int winNums[], int size) { int nums = 0; for(int i = 0; i < size; i++) for(int j = 0; j < size; j++) if(userNums[i] == winNums[j]) nums++; return nums; } This function will return how many numbers are...
68,778,150
68,778,338
Is casting and accessing an array of correct alignment and size to a not constructed Trivial Type undefined behaviour?
Is the following code well defined? struct S { int x; }; alignas(alignof(S)) char c_arr[sizeof(S)]; S *s_ptr = (S*)c_arr; s_ptr->x = 5; // UB or not UB? Note: S is purposfully defined as a Trivial Type. Would the situation change if we made the type none trivial by adding a constructor that just sets X to some arbitra...
Is the following code well defined? No. It violates the so called strict aliasing rule. You must launder the pointer: S *s_ptr = std::launder(reinterpret_cast<S*>(c_arr)); s_ptr->x = 5; // not UB Prior to acceptance of proposal P0593R6, laundering would not have been sufficient. Instead, it used to be necessary to ...
68,778,175
68,778,287
Returning enums by value or reference in C++ and possibility of subset of enums
Consider following scenario: I need to process fruits which most of the time I get in combinations [but not always, lets assume] so I created enum as shown below : enum class ProcessInputFruits {None, Apples, Mangoes, PineApples, Grapes, GrapesAndMangoes, ApplesAndPineApples, All}; In my function ProcessFruits I am pa...
A way to be able to detect overlapping elements, is that you can define enums like: enum class Fruits { None = 0, Apple = 1 << 0, Grape = 1 << 1, Mango = 1 << 2, /* Others */ // You can define their overlap but it's not needed All = Apple | Grape | Mango, }; This way each bit represents whe...
68,778,339
68,778,606
Why does C++ lambda overloading not behave as expected?
#include <type_traits> template<typename T, typename... Args_> concept IsCallable = std::is_invocable_v<T, Args_...>; struct A { int n = 0; void f(IsCallable<int&> auto const fn) { fn(n); } void f(IsCallable<int const&> auto const fn) const { fn(n); } }; struct Lambda { ...
Your question is nearly a duplicate of Hard error when using std::invoke_result_t with a generic lambda . As with the other question, your code will work the way you expect, if you change the lambda so that it has an explicit -> void return type, thus avoiding return type deduction. The difference between your questio...
68,778,728
68,778,808
Retrieve and set file details using windows API?
I'm not able to programmatically get/set file details on Windows. I managed to get file size, creation time, last access, but those are information I don't actually need. I'd like to get/set information like "Author" or "Tag" or every other information you can see in the Details tab in the Properties window of a file, ...
These are properties. Here is a how-to example: https://github.com/microsoft/Windows-classic-samples/tree/main/Samples/Win7Samples/winui/shell/appplatform/PropertyEdit In case the link above will break, here are the core functions to use: SHGetPropertyStoreFromParsingName This will return a IPropertyStore You can enume...
68,779,028
68,779,597
Is there really an Anonymous class/struct in C++?
I'm confused by many websites: People there refer to a class/struct as Anonymous when it has no name for example: struct{ int x = 0; }a; I think the example above creates an Unnamed struct but not an Anonymous struct. I think an Anonymous struct/class doesn't have a name nor a declarator after the close-curly brace...
In the terminology of the C++ standard (N4659), only unions can be "anonymous". Neither the phrase "anonymous class" nor "anonymous struct" appear anywhere in the standard. In fact, the word "anonymous" itself appears only 44 times in the standard: 42 times followed by the word "union", and twice on its own underneath ...
68,779,360
68,779,385
String assignment by each element
I wrote a string assignment in c++, but I don't know why it output s[0], while output none of s? The code is following, and the output is: h**hello* #include <iostream> #include <string> using namespace std; int main(){ string s; s[0] = 'h'; s[1] = 'i'; string s2; s2="hello"; cout <<s[0]<<"*"<< ...
For std::string, operator[] is only valid to index into existing data of the string. It does not cause the string to grow, it simply goes out of bounds if the string isn't already that size. To append to a string, you have several options, but to append single chars like you're doing, you'd do this: int main(){ s...
68,779,537
68,779,562
Getting C++ Function Address using VSCode & VS
I've tried this piece of code in my VSCode, and theoretically the output should give me the function's address #include<iostream> using namespace std; int getNumber(){ return 9000; } int main(){ cout<<getNumber<<endl; return 0; } Once I run the code in VSCode, the output is: 1 So I asked my friend to run ...
std::ostream::operator<< has an overload for bool and a pointer can be implicitly converted to a bool, so the output from VSCode (where you tell us you are compiling with mingw) is correct. Since the address of function getNumber is bound to be non-zero, this becomes true, which equals 1, when converted to a bool, so ...
68,779,701
68,779,781
Can I run different logic for a function returning reference depending on whether it's used as lvalue or rvalue?
Consider the following code: #include <iostream> struct Foo { int x; int& val() { return x; } }; int main() { Foo foo; foo.val() = 2; int y = foo.val(); } In the main function, foo.val() is sometimes used as lvalue and sometimes as rvalue. I would like to to put logic inside the definition of val(...
In the main function, foo.val() is sometimes used as lvalue and sometimes as rvalue. I would like to to put logic inside the definition of val() function depending on how it's being used. Is that possible There is no straightforward way to do what you want. However, you could wrap the integer inside a wrapper class a...
68,779,716
68,779,898
OpenGL rotate around global axis using glm::rotate
I am trying to rotate my model around the global axis. This is what I have: I created a method that would process the user input. If the user presses A or D, the model will rotate 90 degrees to the left or to the right around the Z axis. If the user presses W or S, it will rotate 90 degrees forward or backward around t...
The rotations in your code are cumulative, so if you rotate a airplane for instance, along the yaw (y-axis), then pitch up (x-axis), it'll pitch nose-up in the model's local space, no matter where it yaw'd first, instead of in the global space. To have a global transform, you'd need to actually change the order of your...
68,779,959
68,782,989
Why is `net::dispatch` needed when the I/O object already has an executor?
I'm learning Boost.Beast & Boost.Asio from this example libs/beast/example/http/server/async-ssl/http_server_async_ssl.cpp - 1.77.0. As far as I know, all I/O operations that happen on a I/O object happen in the I/O execution context of the object. The asynchronous operations will be in the same thread as the run of th...
Does it imply that all I/O operations that happen on the new connections happen in the strand? It means that the accepted socket gets a copy of the executor that refers to the strand. This does mean that all async operations initiated from that service object will by default (!) invoke their completion handlers on th...
68,780,116
68,781,388
Is there any alternative for /proc in macOS?
There are no /proc in macOS, however I want to get infomation about my system such as: /proc/loadavg /proc/cpuinfo /proc/meminfo /proc/mounts /proc/stat Is there any alternatives in macOS for that?
In MacOS, you can get all this informations in CLI with sysctl command. sysctl -a //for all information or sysctl hw.memsize //for memory sysctl hw.ncpu //cpu info
68,780,140
68,780,247
inherit base class's constructor
For the following code: struct Base { protected: Base(){} Base(int) {} }; struct Derive : public Base { public: using Base::Base; }; int main() { Derive d1; Derive d2(3); } Seems d1 can be constructed correctly, but d2 cannot be constructed. SO my question is: Why using Base::Base can only chan...
The using-declaration makes the Base constructors visible for overload resolution but with the same accessibility that the constructor has in the base class. If the using-declaration refers to a constructor of a direct base of the class being defined (e.g. using Base::Base;), all constructors of that base (ignoring me...
68,780,287
68,874,668
How to get the minimum XOR of a given value and the value from a query of range for a given array
Given an array A of n integers and given queries in the form of range [l , r] and a value x, find the minimum of A[i] XOR x where l <= i <= r and x will be different for different queries. I tried solving this problem using segment trees but I am not sure what type of information I should store in them as x will be dif...
I was able to solve this using segment tree and tries as suggested by @David Eisenstat Below is an implementation in c++. I constructed a trie for each segment in the segment tree. And finding the minimum xor is just traversing and matching the corresponding trie using each bit of the query value (here) #include <bits/...
68,780,296
68,780,337
Why can't emplace accept begin and end as parameter
I'm developing a basic(low-level) c++11 library for my team. Now I'm trying to develop a custom container. template<typename T1, typename T2> class CustomMap { public: void insert(const std::map<T1, T2>& container) { mp_.insert(container.begin(), container.end()); } void emplace(std::map<T1, T2>&& container) { ...
emplace takes arguments to pass to the constructor of the contained elements of the sequence. In this case, it's a std::pair<const Key, Value>, so when you call emplace the arguments you provide are passed to the constructor of a std::pair. As two iterators are not valid arguments, it won't compile. These examples ar...
68,780,482
68,780,798
Declaring multiple implementations of single function using concepts
I want to be able to define method implementations for types using Concepts (C++20). Value struct declared in value.hpp template <typename T> struct Value { T value; Value(T val) : value(val){}; // For example I'll use `operator bool()` constexpr operator bool() const; // T can literally be anything...
You can certainly define multiple overloads of function templates, or member functions of a class template, with constraints, but they must be just that—overloads. You can’t just declare one member function and then provide it several implementations. So declare them all inValue—including the implementations, for sim...
68,780,740
68,780,887
Why is my VS code terminal not running the code?
The terminal works fine while running my previous codes except the recent one. Most likely there's some error in my code but I tried running the same in an online compiler and it worked just fine. Here's the screenshot of the terminal: Here's my code: #include<bits/stdc++.h> using namespace std; void stair_search(int...
Try adding a try/catch block to your functions and see if you get an error. Like this: void stair_search(int a[][1000], int row, int col, int k){ try{ int i=0, j=col-1; while(i < row and j >= 0){ if(a[i][j] == k){ std::cout<<k<<" found at "<<i<<", "<<j<<"\n"; return; } if(a[i][j] > k){ ...
68,780,932
68,781,051
What is the fastest way to pause execution in c++
I would like to pause execution time in c++ and this is the code I got: while (_run) { //pause code std::this_thread::sleep_for(std::chrono::nanoseconds(_interval_ns)); //doing stuff _counter++; (*_mainSrcTick)(GetDeltaTime(), GetName()); for (auto obj : _physicsList) { PyObjec...
When you ask your thread to sleep, it is unscheduled by the operating system, and rescheduling it takes some time. If you want to pause for a very small amount of time, use _mm_pause(). You may want to do it a fixed number of times based on your own measurements of how long it takes on your system. Intel says it tak...
68,781,072
68,781,097
How to define a nested template
I defined a function as below, which took an integer as a template parameter, it worked as expected. template<int D, typename std::enable_if<std::greater<int>{}(D, 100), void*>::type = nullptr> void func(int p) { // something } func<100>(1); // ERROR func<101>(1); // OK Now, I want to make the int as a template pa...
You need to declare T as type template parameter firstly. E.g. template<typename T, T D, typename std::enable_if<std::greater<T>{}(D, 100), void*>::type = nullptr> void func(int p) { // something } then func<int, 100>(1); // ERROR func<int, 101>(1); // OK If you don't want to specify int explicitly, you can templ...
68,781,595
68,781,862
Why std::binary_search on an array give different results in cmd and linux terminal?
I was trying to solve a codeforces problem, which required me to find the interior angles of polygons using the formula: ((n-2)*180)/n ; where 'n' is number of polygon sides. I took an array of size: 5 to store the angles of triangle(n=3) and square(n=4). The following code was written to search for an angle(60 degre...
The fact that you got different answers is due to the undefined behavior generated by the fact that a chunk of the array is not initialized. But if you really want to understand why the first compiler gave an answer different from the second, it's necessary to see the machine code generated by each compiler. Here and h...
68,781,751
68,781,810
Can `throw` be inside a comma subexpression within C++ conditional (ternary) operator?
It is well known that throw can be placed as the second or the third operand of C++ ternary operator ?:. But can it be inside a comma subexpression of there operands? It looks like compilers diverge in this regard. Please consider an example: #include <iostream> void foo(bool b) { int i = b ? 1 : (throw 0); //ok e...
Clang and GCC are correct to reject it. It's pretty straightforward: [expr.cond] 2 If either the second or the third operand has type void, one of the following shall hold: The second or the third operand (but not both) is a (possibly parenthesized) throw-expression ([expr.throw]); the result is of the type and value...
68,781,855
68,781,929
How to fill an Eigen Vector with another Eigen Vector?
I have a defined Eigen vector1 and an undefined Eigen vector2, how do i fill vector2 with values of vector1 and subsequent data (doubles) like: Eigen::RowVectorXd vector1 = Eigen::RowVectorXd::Ones(1); Eigen::RowVectorXd vector2; vector2 << vector1, 2.0, 3.4 // Gives AssertionError
The << operator can only be used to fill an Eigen::Vector if its size corresponds to that of the supplied data. You could either declare the vector with the correct dimension Eigen::RowVectorXd vector2(vector1.size() + 2); or resize it vector2.resize(vector1.size() + 2); before using the << operator to fill in the va...
68,782,318
68,782,395
I want to know why it can be successful with vecter but not array?
This succeeds: #include <iostream> #include <vector> using namespace std; int test(vector<int> items) { for (int item : items) { cout << item; } return 0; } int main() { vector<int> items = { 1, 2, 3 }; test(items); return 0; } This fails: #include <iostream> using namespace std; ...
Arrays cannot be passed to functions by value. This signature int test(int items[]) is equivalent to int test(int* items) A pointer has no begin nor end and there is no way to deduce the size of the array from the pointer alone. In your second example items in main is an array (remember: arrays are not pointers), and...
68,782,386
68,782,555
C++ - calling a member function of another class using a pointer
I'm testing, trying to call a member function being passed as a parameter, the member function has to be one of another class. this is an example, which gives an error: "pointer-to-member selection class types are incompatible ("B" and "A")" This is the code, what am I doing wrong? #include <iostream> using namespace...
&(a.fA) is not legal C++ syntax. &A::fA is. As you can see, there is no object of type A anywhere of this syntax. &A::fA is just a pointer to a member function, not a pointer-to-member-together-with-an-object combo. Now in order to call that pointer-to-member, you need an object of class A. In class B, you don't have a...
68,782,979
68,784,465
How to create a CMakeLists.txt for a gtkmm application?
My Application tree is as follows: ├── build ├── CMakeLists.txt ├── example │   ├── applicationwindow.cpp │   ├── applicationwindow.h │   └── Application.glade └── main.cpp 2 directories, 5 files And the CMakeLists.txt file I created is as follows: cmake_minimum_required(VERSION 3.1.0) project(Example_App) set(CMAKE_...
Since you seem to be new to CMake, I will add some code around the answer provided by mohamadp91. Your problem is that when you are running cmake .., the Application.glade file is never copied into the build directory, when you run make and execute your software. At this point, the application tries to load a build/exa...