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
72,718,155
72,718,374
Bring to derived object the assignment operator from base (prior to C++11)
I have a code similar to this: template <typename T> struct B { B &operator =(const T &) { return *this; } }; struct D : B<int> {}; int main() { D d; d = 0; return 0; } Which fails: error: no viable overloaded '=' d = 0; ~ ^ ~ note: candidate function (the implicit copy assignment operator) no...
First things first, the program(with using declaration) works with C++98. Working Demo with C++98. That is, a using declaration for the assignment operator of the base class inside the derived class is allowed by C++98. Here is the relevant text from the standard: If an assignment operator brought from a base class in...
72,718,417
72,719,182
Is declaring a friend which is forward-declared in an unnamed namespace an ODR-violation?
I've been using a dirty trick where I use unnamed namespaces to specify different behavior for each file (it is for unit-testing). It feels like it shouldn't be well-defined, but it works on every major compiler released in the past six years. I first forward-declare a bunch of classes in an anonymouse namespace: names...
Seems to violate the following condition required by ODR, as stated on https://en.cppreference.com/w/cpp/language/definition: There can be more than one definition in a program of each of the following: class type, [...], as long as all of the following is true: [...] name lookup from within each definition finds the...
72,718,956
72,719,150
Create method that accepts method from any child class
I apologize for the vague question title, but I'm unfamiliar enough with C++ to be able to phrase it better. I'm trying to create a method that takes a method on any child class as one of the parameters, but I'm getting a compiler error that I don't know how to fix. I'd also like to alias the type so it's not so verbos...
You can cast the child class member function pointer to the type of a base class member function pointer. static_cast<my_handler_type>(&ChildClass::some_handling_function)); So: #include <iostream> #include <map> #include <string> using std::map; using std::string; struct ParentClass; struct DataClass {}; using my_...
72,719,009
72,719,185
How can I test whether a type is a range from which I can move elements?
Assume that I have a function template that can accept a range of some type T. I want to check whether it's safe to move from that range. For example, if a function accepts an rvalue reference to a certain value, it is safe to move from it. If, for example, that function may accept both rvalue and lvalue references, we...
I would suggest making it up to the caller to tell you this by using a range adaptor that produces rvalue references (views::move in range-v3, views::as_rvalue proposed for C++23). That way you don't have to guess, since you'll get a range of rvalues: algo(vec); // can't move algo(vec | views::move); // can move algo(v...
72,719,181
72,720,263
How to place my function using QSignalMapper and QObject::connect
I'm a beginner in c++. i'm trying to pass an argument using QSignalMapper. I do something like this: int main(int argc, char** argv) { ... QSignalMapper * mapper = new QSignalMapper(0); QObject::connect(mapper,SIGNAL(mapped(int )), 0 ,SLOT(mySlot(int ))); int prova=11; mapper->setMapping(but, prova...
Forget about QSignalMapper and use lambdas: QObject::connect(but, &QButton::clicked, myObject, [myObject,prova]() { myObject->mySlot(prova); }); In case mySlot is just a regular function: QObject::connect(but, &QButton::clicked, [prova]() { mySlot(prova); });
72,719,193
72,719,309
How to initialize static members of two various types of template class
I want to assign two different values to A<int> and A<char>,then each kind of instantialized classes have their own static member 'a',but the program compile failed. Here's the code. #include <iostream> using namespace std; template<class T> class A { private: static int a; public: friend ostream& operator<<<T...
You need to do an explicit specialization which you do by writing an empty template declaration and replacing T in A<T> with the type you want. template<> int A<int>::a = 5; template<> int A<char>::a = 50;
72,719,605
72,720,127
Segmentation fault on Eigen::SparseMatrix resize
I have a large set of codes (public on github), but it's way too much to put in a question, and I have no idea how to get a mwe (you'll see why), so I'd be happy with just some more suggestions on what could be going wrong. We have a class, SC_class, in this file, with several derived classes. In the derived class Cyli...
Okay, strangest source of the error; I don't know if anyone else will have something like this, but just in case, I'll share. I have a pointer in the main file, but I eventually turn it into an array. At the end of the program, I delete that pointer as if it was an array (since that's what I turned it into), but that w...
72,719,624
72,719,665
Fixed-size array as function parameter: No matching function for call to 'begin'
I am passing a fixed size array to a function (the size is defined to a constant in the function's definition). However, I still get the error No matching function for call to 'begin' # define arr_size 2 void test(int arr0[2]){ int arr1[]={1,2,3}; int arr2[arr_size]; begin(arr0); // does not work -- ...
This function declaration void test(int arr0[2]){ is equivalent to void test(int *arr0){ because the compiler adjusts parameters having array types to pointers to array element types. That is the both declarations declare the same one function. You may even write for example void test(int arr0[2]); void test(int *ar...
72,720,101
72,720,351
Deduce template parameter value from concept
I continue my C++20 concept(ual) jourrney... I would like to simplify the following code by deducing the template parameter T from the predicate argument, so that the client code does not have to precise the type of T if it can be deduced from P1. I guess it is possible, I just don't know the syntax: I tried various fo...
std::function has good deduction guides to get the type of a callable: // Replacement for `std::function<T(U)>::argument_type` template<typename T> struct single_function_argument; template<typename Ret, typename Arg> struct single_function_argument<std::function<Ret(Arg)>> { using type = Arg; }; // Deduction guide te...
72,720,175
72,720,353
Is there some way to specify if template param of function is specific template class?
I will explain my question based on following example: template <typename Param1, typename Param2> class foo1 { void lol(); }; template <typename Param1, typename Param2> class foo2 { void lol(); }; ////////////////////////// FIRST OPTION ////////////////////////// template <typename Param1, typename Param2> voi...
The template parameters are used. Without them, foo1 and foo2 are just class templates and not a classes. A simple way to minimize the typing would be to use template parameter packs: template<class... T> void func(foo1<T...> a) { a.lol(); a.lol(); } template<class... T> void func(foo2<T...> a) { a.lol(); ...
72,720,226
72,720,320
Iterate through array denoted by unsigned short pointer
I have some code that existed in C which contains an array of uint16_t, which looks something like uint16_t *Fingerprints;. To iterate through it, I can pair it together with a uint32_t ArrayLength; value and directly access Fingerprints[i]. Now, I am writing more code in C++ and I have a std::vector<uint16_t> values t...
std::vector<uint16_t> has a .data() member function which will give you a uint16_t* pointer and which you could use together with .size() in the same way you were using it in C. However, in C++ we usually use iterators instead of pointers if there is no specific reason to use the latter. Iterators are a generalization ...
72,720,251
72,720,345
C++ Overwrite initializer list in unit test
I have some C++ code like this that I want to unit test: class Example { private: ExpensiveObject expensiveObject; public: Example() : expensiveObject() { ... constructor code } methodA() { ... some code } } To write a unit test for met...
expensiveObject cannot be assigned null. What you might want is to have a smart pointer to ExpensiveObject, and have multiple constructors or better you want to inject your dependencies. class Example { private: std::shared_ptr<ExpensiveObject> expensiveObject; public: Example(std::sha...
72,720,684
72,720,880
Check bitfield value in static assert?
I wrote a library that requires little endian and bitfields to be ordered from low to high I run similar code at runtime to check it. I was wondering if I could do this at compile time? #include <cstring> #include <cassert> #include <cstdio> #include <cstdint> struct A { uint64_t a : 4, b : 5, c:55; A()=defaul...
You can replace the memcpy with bit_cast to make your constructor constexpr: #include <bit> #include <cstdint> struct A { uint64_t a : 4, b : 5, c:55; A()=default; constexpr A(uint64_t value) { *this = std::bit_cast<A>(value); } }; static_assert(A(0x3F3).a == 3); static_assert(A(0x3F3).b == 0x1F); static_...
72,720,891
72,721,201
Losing messages when multiprocess logging with easylogging++ in C++
I'm using easylogging++ in my app to log messages for control and I've noticed that in production env (which runs under Linux) some messages were disappearing or missing from the log files. I managed to simulate this problem with a simple example in the test environment (on Windows). I made an infinite thread that just...
I guess that one solution could be just using different log files for each process, however it doesn't happen in one single process with multiple threads (instantiating thread t1, t2,t3 as in the code example before) Well, threads in a single process share an instance of std::mutex mtx, so they're properly synchroniz...
72,721,110
72,721,180
Casting int64_t * to uint64_t *
The signed integer pointer is the output of some_vector.data() of a std::vector<int64_t> some_vector, but I know all the values are positive and I want to cast that integer to an unsigned integer. How can I do that and "reinterpret" the vector values as unsigned?
You can simply cast the pointer to the desired type and I think this will almost always work: uint64_t * data = (uint64_t *)some_vector.data(); However I am not sure if this is allowed or safe according to the C++ standard. (Search for "strict aliasing" to learn about one type of pitfall.) And someone will probably ...
72,721,520
72,723,275
How can you wrap a C++ function with SWIG that takes in a Python numpy array as input without explicitly giving a size?
I have a library of C++ classes that I am building a Python interface for using SWIG. Many of these classes have methods that take in a double* array or int* array parameter without inputting a size. For example, there are many methods that have a declaration like one of the following: void func(double* array); void f...
One way I can think of is to suppress the "no size" version of the function and extend the class to have a version with a throw-away dimension variable that uses the actual parameter in the class. Example: test.i %module test %{ #define SWIG_FILE_WITH_INIT class Test { public: int _dim; // needs to be public, or ...
72,721,710
72,722,494
Integer initialization of enum outside of range
I am reading Bjarne Stroustrup's "Tour of C++" (2:nd edition). In chapter 2.5, he discusses enums with the following example: enum class Color {red,blue,green}; In the same chapter, he says that it is allowed to initialize an enum with a value from its underlying type (int by default), and gives the following example:...
This comes from C: enumerated types are fancy integers. The names of the enumerations are handy, but they don't define every value that the type can represent. Probably the most common use for an enumerated type is, though, as a simple list of constants: enum state [ off, starting, running, shutting_dow...
72,722,731
72,722,942
JSON extract date from matching string
I am entirely new to JSON, and haven't got any familiarity with it at all. I'm tinkering around with some JSON data extracts to get a feel for it. Currently, I have a chat export which has a large number of keys. Within these keys are a "date" key, and a "from_id" key. I would like to search a JSON file for a matching ...
you can try this c# code. At first you have to parse your json strig to create an object from string. Then you can use LINQ to get the data you need using Newtonsoft.Json; JArray messages = (JArray) JObject.Parse(json)["messages"]; string from_id="user1234"; DateTime[] dates = messages .Where(m=> (st...
72,723,099
72,723,161
socket write in for loop mixes string buffers
I call a function multiple times using a for loop like this: for ( int con=0; con < this->controller_info.size(); con++ ) { try { this->pi.home_axis( this->controller_info.at(con).addr ); } catch( std::out_of_range &e ) { ... } } where the home_axis() function is defined as: long ServoInterface::home_axis( i...
This has nothing to do with the compiler at all. TCP is a byte stream. It has no concept of message boundaries. There is no 1:1 relationship between writes and reads. You can write 2 messages of 6 bytes each, and the receiver may receive all 12 bytes at a time, or 1 byte and then 11 bytes, or any combination in betw...
72,723,371
72,723,395
c++20 why can't I "pipe" into views::reverse like the other views functions?
I am testing some of the fancy new c++ features, one of which is ranges and the associated views. I find it particularly interesting that you can chain what you wish to do with a container. You can use the binary operator|() to chain things, which is really nice. I noticed that you can chain into std::views::take(int),...
The syntax for piping into single-argument adaptors isn't: | views::reverse() It's | views::reverse No parentheses in this case. std::views::reverse(a) could be written as a | std::views::reverse to start with as well. Similar for all the other single-argument range adaptors (join, keys, values, elements<N>, etc.).
72,723,704
72,724,206
'ld' Error while compiling a module (Ubuntu 22.04)
I am trying to compile a module https://github.com/In-line/grip I have installed the below tools sudo dpkg --add-architecture i386 sudo apt-get update sudo apt-get install -y gcc-multilib g++-multilib sudo apt-get install -y build-essential sudo apt-get install -y libc6-dev libc6-dev-i386 sudo apt-get install -y cmake ...
One of my friend suggested to do apt install lld and the issue got resolved.
72,725,311
72,727,561
Is this good practice for reading into a string in C++?
I have a function in C++ which reads the contents of a HTTP request body into a std::string. I came up with the following code: void handle_request_body(int connfd, HttpRequest &req) { unsigned long size_to_read; try { size_to_read = std::stoul(req.headers().at("content-length")); } catch (std::out_of_range c...
Really depends what your read function does under the hood. If you have control over the read function, I strongly suggest you don't use a pointer, but rather a class reference to a std container. The resizable std containers don't guarantee that the pointers will keep pointing at the same memory i.e. if it reallocates...
72,725,329
72,725,414
In C++, why must class member functions be defined outside class for separate compilation?
The following is a simple example for separate compilation: // mod.cpp #include <cstdio> class MyModule { public: void print_msg(); }; void MyModule::print_msg() { printf("hello from module\n"); } // main.cpp class MyModule { public: void print_msg(); }; int main() { MyModule a; a.print_msg(); }...
Functions defined inside the class are implicitly inline. C++ requires: The definition of an inline function [or variable (since C++17)] must be reachable in the translation unit where it is accessed. Since you only defined it in mod.cpp, no definition is reachable in main.cpp, and compilation fails. Typically, you'd...
72,725,762
72,725,849
Why universal reference as an input parameter doesn't work
template<typename T> constexpr auto log_value(T&& value) { if constexpr (std::is_enum_v<T>) { cout << "enum" << endl; } else { cout << "normal" << endl; } } I have a function to judge whether some value is an enum, and I test it by enum class A { a, s, d }; int main() { ...
The way forwarding (aka universal) references work for lvalues is by deducing the referenced type (T in your case) to an lvalue reference (A & in your case). Then T && also becomes A & according to the reference collapsing rules (& + && = &). For rvalues this is not needed, and T is deduced to a non-reference. You want...
72,726,793
72,732,652
Unexpected compilation errors when targeting ARM
I am trying to rebuild existing C++ code for the ARM64 platform using Visual Studio 2022. (The build works well for the x86 and x64 platforms.) Most of the compilation succeeds but for one file that uses some Win32 API calls. I am getting dozen messages like Error C3861 '_InterlockedIncrement': identifier not found...
I finally found the cause. Here is how I proceeded: I removed all files from the whole project, except the offending one (checked that the problem was still there); I added that file to the dummy project (the problem was not showing there); I compared the project files, but this told me nothing because they were too...
72,727,086
72,728,832
The P/A deducation when determining the partial order of C++ overloaded function templates
In cppreference.com, there is an example: template<class T> void f(T, T*); // #1 template<class T> void f(T, int*); // #2 void m(int* p) { f(0, p); // deduction for #1: void f(T, T*) [T = int] // deduction for #2: void f(T, int*) [T = int] // partial ordering: // #1 from #2: void(T,T*) ...
For each type, non-type, and template parameter, including parameter packs, a unique fictitious type, value, or template is generated and substituted into function type of the template U1 here is not a template type; it's a unique ficitious type and it's different from int, so the deduction fails.
72,727,268
72,727,368
how to show a variable in MESSAGE_TEXT in signal query in c++
I am using Signal query to catch errors in my c++ programming: in the program user has to enter a database name and i check the database if it does not exists I have to return proper error message: std::string database_name; std::cin<<database_name; if(!exists(database_name)){ query="SIGNAL SQLSTATE '42000' SET MYSQL...
You can format the string using query = std::format( "... MESSAGE_TEXT = 'Unknown database {}'", database_name ); This will replace {} with the first string argument (database_name) Or you could use a string stream like std::ostringstream ss; ss << "... MESSAGE_TEXT = 'Unknown database '" << database_name << "'"; quer...
72,727,396
72,727,629
Member function doesn't work when using pointer to class
Scenario: I have two classes, each contains a pointer to the other (when using them, being able to refer to the other is going to be important so I deemed this appropriate). When I try accessing a private variable from one class via using the pointer to the other and a getter function inside that, it works perfectly. P...
This is quite simple: Your getTeam() and getDriver() functions are returning copies of the objects, not references, so the addPoints() are performed on temporary copies and not the real ones. To fix it, simply change the return types to references (add &): Team& getTeam(); and Driver& getDriver();
72,727,684
72,728,992
make using namespace global from c++ module
I am trying to expose a c++ namespace to whatever includes that c++ module. Usually in a header file I can just write using namespace x::y::z; and it'll work. I couldn't get it to work from a module. I am using visual studio 2022 with MSVC v143, c++ latest.
In the current standard draft § 10.2 [module.interface], we see: export using namespace N; // error: does not declare a name In the same section, there are also correct exports of non-namespace using declarations export using T = S; // OK, exports name T denoting type S and I believe that namespac...
72,728,374
72,737,017
Qt5.9.6 do not follow RPATH to search openssl
I'm working on Qt based project on Linux based OS. We use Qt5.9.6. When we launch our application, we've got this log from Qt qt.network.ssl: Incompatible version of OpenSSL After a few research I found that Qt loads the version 1.1 of openssl whereas Qt5.9.6 needs the 1.0.2k version. So I put the right version of op...
So the thing is, Qt loads the OpenSSL library as a plugin, and the dynamic linker ld.so on Linux only takes into account the rpath of the executable and/or shared object that calls dlopen(). And because Qt itself doesn't have the rpath for your OpenSSL copy set, it won't load it. The best way around that is (as long as...
72,729,549
72,729,723
OpenCV Mat::convertTo(type) does not convert the type
GIVEN: The following code fragment: #include <opencv2/core.hpp> #include <iostream> int main(int argc, char** argv) { cv::Mat a = (cv::Mat_<double>(3,1) << 1, 2, 3); cv::Mat b; std::cout << "a(before): " << cv::typeToString(a.type()) << std::endl; std::cout << "b(before): " << cv::typeToString(b...
Short answer: cv::Mat::convertTo does not support changing the number of channels. Longer answer: As you can see in the documentation regarding the rtype paremeter of cv::Mat::convertTo (the one you pass CV_64FC4 to): desired output matrix type or, rather, the depth since the number of channels are the same as the inp...
72,729,727
72,745,602
Standard layout, taking address of member and indexing past it to next member
Suppose we have a standard-layout class, simplified to this: struct X { int num; Object obj; // also standard layout char buf[512]; }; As I understand it, if we have an instance of X, we can take its address and cast it to char* and look at the content of X as if it was an array of bytes. However, it's a l...
As I understand it, if we have an instance of X, we can take its address and cast it to char* and look at the content of X as if it was an array of bytes. The standard doesn't actually allow this currently. Casting to char* will not change the pointer value (per [expr.static.cast]/13) and as a result you will not be ...
72,729,861
72,732,725
Enabling ANSI escape sequences on Windows let disable some Unicode sequences. How to Solve?
I recently enabled ANSI escape sequences on my Windows console using this functions defined in an header my_windows.h: #ifndef WINDOWS_HPP #define WINDOWS_HPP namespace osm { extern void enableANSI(); extern void disableANSI(); } and implemented in my_windows.cpp #ifdef _WIN32 #include <windows.h> #endif #incl...
Thanks to PanagiotisKanavos i solved the issue by using the chcp 65001 command. The problem is that if I am on MSYS2 I am unable to run this command from the shell: therefore I used the system() function to call it directly in my code, since my executables run directly on the Windows shell: // code without using ANSI e...
72,729,926
72,730,820
C++ - I want to show a set of random dice, but I can't find out how
I'm fairly new to this, been writing code for ~3 months and now I have to make a dice game for a group project. So far, the console shows what I expect it to show (5 random dice values) But what I want to do to improve it is to show an actual die instead of an individual number, like ⚀⚁⚂⚃⚄⚅ These are the functions I'v...
But what I want to do to improve it is to show an actual die instead of an individual number, like ⚀⚁⚂⚃⚄⚅ Note those characters are non-ASCII. So to make it work you have to take care of encoding of characters (encoding) for each step (source, building, running on some specific system). At final step terminal used ha...
72,729,944
72,752,985
Search String Highlight in qt or qml
I have use case where in text entered in TextField (Qml Component) should highlight all the texts which matches in the list view content. I have explored many blogs, in every blog I can just see the snippet code. But not the complete usage, so I couldn't find any proper solution. Can anyone help me out with sample work...
The simple example using Text as a delegate: ColumnLayout { anchors.fill: parent spacing: 5 TextField { id: input Layout.preferredHeight: 30 Layout.fillWidth: true } ListView { id: list Layout.fillHeight: true Layout.fillWidth: true model: ["a...
72,730,020
72,732,772
Is there a compilation flag to detect duplicate lamda parameter-lambda member?
This code compiles with g++, no collision is detected, although s is the parameter captured by lambda and the lambda parameter. My compiler is g++. gcc Version is gcc (Debian 4.9.2-10+deb8u2) 4.9.2 Copyright (C) 2014 Free Software Foundation, Inc. and I am using these compilation flags : -W -Wall -ansi -pedantic -s ...
Upgrade your compilers. Based on https://godbolt.org/z/h3Y7dW1dP that warning is missing for gcc 8.5 (with -std=c++17) and clang 7.1.0. You should upgrade to gcc 9.1 and clang 8.0.0 or later. (Preferably a lot later.)
72,730,038
72,731,043
Creating object on stack, from a class with dynamic members
Assume we create an object on stack as class Test{ Test(int i) {i_=i;} Test(std::vector<int> v) {v_=v;} int i_; std::vector<int> v_; }; int main() { Test a; // how much memory is occupied/reserved now for a? . . . return 0; } How compiler determines the required size for "a", when it is not yet known which construc...
How compiler determines the required size for "a", when it is not yet known which constructor is going to be called? This question hinges on two misunderstandings: First, Test a; does call the default constructor. Next, the size of objects to be allocated on the stack is a constant: sizeof(Test). This size does not c...
72,730,133
72,735,454
unordered_map: Lookup pair of std::string with a pair of std::string_view
Given a hashmap that is keyed on a pair of strings, e.g: std::unordered_map<std::pair<String, String>, int> myMap; How could one do a lookup with a pair of std::string_view, e.g: std::string s = "I'm a string"; std::string s2 = "I'm also a string"; std::string_view sv(s); std::string_view sv2(s2); myMap.find(std::make...
With C++20's heterogeneous lookups this can be done (see documentation of unordered_map::find()). For this to work a hash functor and a equality functor have to be defined, e.g.: struct hash { template <typename T> auto operator()(const std::pair<T, T>& pair) const { return std::hash<T>{}(pair.first) ^ ...
72,731,302
72,731,379
How to directly input RGB(A) values in textures in C++/OpenGL?
I want to dabble in some procedural textures in an OpenGL project, but nothing seems to work. All I need is to input the RGB and maybe A values into an empty texture, instead of loading it from a file. How do I do this, in actual, practical code? Edit: There is no main code yet, because I have found nothing that works....
Create an array of data and load it into a texture image: uint8_t image_data[4] = {255, 0, 0, 255}; // red GLuint tex_obj; glGenTextures(1, &tex_obj); glBindTexture(GL_TEXTURE_2D, tex_obj); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data);
72,731,594
72,732,080
Reserve 2D Vector in C++ and copy data from array
I hope to use vector to process the 2d array data obtained by calling a third-party library. Although I can simply use the loop to assign values one by one, But I prefer to use methods such as insert and copy to deal with this. I found that reserve doesn't seem to work here. So I used resize instead. double **a = new d...
If the size of the source array is fixed, it is strongly recommended to use std::array instead of std::vector. std::array has continuous memory layout for multidimensional structures, thus std::memcpy can be used for copy if the source array is also continuous in memory. Look back to the original question. If you want ...
72,731,652
72,738,165
Delete elements of vector from other vector
I want to delete all elements of a vector v which are contained by v2; Is this solution good or should I use something else ? #include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { std::vector<int> v = {1,2,3,4,5,1,2}; std::vector<int> v2 = {1,2,3}; v.erase(std::...
It's quite good for small filtering v2. It is a bit better if you pass v2 by reference. v.erase(std::remove_if(v.begin(), v.end(), [&v2](int x) { std::find(v2.begin(), v2.end(), x) != v2.end(); }), v.end()); If v2 is large it is better to replace it with std::unordered_set<int> s. It also removed duplicates i...
72,732,371
72,732,838
Make a common function for a "type" and the vector of "type" using templates in C++
I was writing functions and came across this situation: void doSomeThing(std::vector<someType> vec) { for(element : vec) { // do Something different if it is in vector } } void doSomeThing(someType element) { // do Something else if it was not a vector } I need them to be separate like above stated. I wa...
Well, yes, it is possible. For example, you could do; template<class someType> void doSomeThing( const someType &obj ) { // do something assuming someType is not a vector of something } template<class someType> void doSomeThing( const std::vector<someType> &obj ) { // do something different if a vector<som...
72,733,063
72,754,601
V8 lib and C++ inlining behavior differs from expectations and reproducing in separate project
I'm getting an error trying to construct a v8::ScriptOrigin object. Confirming the compiler error, my IDE only resolves the implicit copy and move constructors. v8_api.cc: error: no matching constructor for initialization of 'v8::ScriptOrigin' v8::ScriptOrigin::ScriptOrigin is marked with V8_INLINE macro which specifie...
Trying to compile this snippet tells you exactly what's going on: $ clang++ -std=c++17 test.cc -o test.bin -Iv8/include test.cc:18:30: error: no matching constructor for initialization of 'v8::ScriptOrigin' auto script_origin = new v8::ScriptOrigin(isolate, v8::String::NewFromUtf8(isolate, "main.mjs")); ...
72,733,405
72,733,776
Inserting iterable containers into map for keys and values
I have two arrays like the following. The arrays are always the same size. std::array<int, 5> keys; std::array<int, 5> values; I want to load them into a map for the keys and values, respectively. std::unordered_map<int, int> map; for (int i = 0; i < keys.size(); i++) { map.emplace(keys[i], values[i]); } Is the...
Yes, you can achieve the goal using STL std::transform with the help of std::inserter. #include <iostream> #include <unordered_map> #include <algorithm> using namespace std; int main() { std::array<int, 5> keys{1,2,3,4,5}; std::array<int, 5> values{10,20,30,40,50}; std::unordered_map<int, int> map; ...
72,734,098
72,734,164
libcpr not working properly when using it for HTTP request
I am using libcpr for http requests in Visual Studio 2019 IDE. I downloaded it using vcpkg from microsoft. The sample code below is from cpr github page https://github.com/libcpr/cpr#:~:text=%23include%20%3C,return%200%3B%0A%7D #include <cpr/cpr.h> int main(int argc, char** argv) { cpr::Response r = ...
Looks to me like a versioning issue. AuthMode exists in the latest header file, but does not exist in the version 1.8 header file, which is presumably what you have. So, either downgrade your code, or upgrade your installation. Sample code from version 1.8 is here
72,734,253
72,734,310
Why does this code report that -31 is greater than 6?
I have a function double max(int count, ...) in my program. This function should return the highest number, but it reports that -31 > 6. Where is my mistake? I'm trying to learn va_. How can I fix this? double max(int count, ...) { double max = INT_MIN, test; int i; va_list values; va_start(values, cou...
You are invoking undefined behavior. You are not passing in double values to max(), you are passing in int values instead. int and double are different sizes in memory, and va_arg() can't read an int parameter as if it were a double, and vice versa. You need to match the types correctly. In this example, change all o...
72,734,558
72,734,728
is `auto ua = unsigned int {};` legit C++?
This code compiles with MSVC, but not with GCC or Clang. auto a = int{}; auto ua = unsigned int {}; See demo on compiler explorer I strongly suspect it might be legit C++, but that the mix between the ancient "C style / types with spaces" and the 50 differents ways of doing initialization in C++ make this a ve...
According to the C++ 20 Standard (7.6.1.4 Explicit type conversion (functional notation)): 1 A simple-type-specifier (9.2.9.3) or typename-specifier (13.8) followed by a parenthesized optional expression-list or by a braced-init-list (the initializer) constructs a value of the specified type given the initializer. If ...
72,735,034
72,735,215
Calling member function before object usage
A few days ago, I was asking about operator overloading to my Logger project. Now I have another problem which I'm not able to solve - probably due to my low experience. First - my Logger object (which is designed as a Singleton object) should write to a file created in the same directory as the source code. Desired us...
Where does your Logger open the file to begin with? Why aren't you doing these checks at the point where the file is being opened? This sounds like something you should be handling in your Logger's constructor, for instance. And, rather than defining a global logger object, consider defining a static method in your Log...
72,735,082
72,735,232
Why does "if (char a = f())" compile whereas "if ((char a = f()))" does not?
#include <iostream> char f() { return 0; } int main() { // Compiles if (char a = f()) std::cout << a; // Does not compile (causes a compilation error) // if ((char a = f())) // std::cout << a; return 0; } One can declare a local variable and assign a value to it insi...
To put it simply, C++ syntax allows the condition inside an if statement to be either an expression or a declaration. So, char a = f() is a declaration (of the variable named a). But (char a = f()) is not a declaration (and is also not an expression convertible to bool).
72,735,235
72,735,517
c++ how to delete thread once it has been terminated
I'm working on a project that uses uses a thread to connect to a server. Whenever the login button is pressed, it initialized a thread to log in with the given IP and port provided by the user. ServerPage.h class ServerPage { public: static std::thread serverThread; static void login(); } ServerPage.cpp #...
First of all: threads cannot be restarted. There is no such concept in programming. Unless by "restart" you mean "kill and spawn again". It is not possible to kill a thread in a cross-platform way. For posix (I don't know about other OS) you can use pthreads (instead of std::thread) and send kill signal to it and spawn...
72,736,095
72,802,162
Cannot compile when I include the Windows.Devices.Enumeration.h file
I have a Visual Studio 2017 C++17 MFC project on Windows 10 using Windows SDK 10.0.18362.0. I need to add code to enumerate and connect to a Bluetooth LE device. To start off, the first thing I need to do is to #include <winrt/Windows.Devices.Enumeration.h> The winrt/ header files are in C:\Program Files (x86)\Window...
As a follow up. The thing that I found that worked was a Project Properties setting. Properties > C/C++ > General node in the left pane. Set the Consume Windows Runtime Extension property to Yes
72,736,631
72,736,840
Logical operations in OpenCV
Assume two Mat CV_8UC1 images, mask, and label, how to do the following operation in OpenCV (C++): mask(label==5) = 255; // this is allowed in Matlab // or mask[label==5] = 255; // this is allowed in Python
You could use inrange() with lowerb and upperb both set to 5, or you could use compare() with src2 set to 5 and cmpop set to cv::CMP_EQ. Both will set the output mask to be 255 where the values match.
72,736,764
72,738,542
How to allow uiAccess in UWP application
I am invoking C++ UIautomation modules in my UWP application. The application is not able to extract control elements since it is not running in an elevated environment. How should I set up the manifest file or set my UWP app to be able to get access to ui elements of other applications.
I'd suggest that you could put the UIautomation modules into a console app and then launch the console as elevated from your UWP app using desktop bridge. You will also need to add the allowElevation capability into the manifest file. For detailed steps, you could take a look at Stefan wick's blog- App Elevation Sample...
72,737,039
72,737,215
Why does Clang add extra FMA instructions?
#include <immintrin.h> __m256 mult(__m256 num) { return 278*num/(num+1400); } .LCPI0_0: .long 0x438b0000 # float 278 .LCPI0_1: .long 0x44af0000 # float 1400 mult(float __vector(8)): # @mult(float __vector(8)) vbroadcas...
The extra FMAs compensate for the reduced precision of vrcpps. ymm3 is an estimate of the result, but at about half the usual precision. For simplicity let's say the division was q = a / b. The first FMA, vfmsub213ps, computes the difference (a * b⁻¹) * b - a, which is an estimate of how much the division was "off" by ...
72,737,316
72,740,574
Is std::move of shared_ptr thread safe?
The following snippet runs fine: #include <memory> #include <cassert> int main() { auto ptr1 = std::make_shared<int>(10); assert(ptr1.use_count() == 1); auto ptr2 = std::move(ptr1); assert(ptr1 == nullptr); auto ptr3 = static_cast<std::shared_ptr<int>&&>(ptr2); assert(ptr2 == nullptr); ass...
You have a misconception about what std::move does. In fact std::move does nothing. It's just a compile time mechanism with the meaning: I no longer need this named value. This then causes the compiler to use the value in different ways, like call a move constructor/assignment instead of copy constructor/assignment. Bu...
72,737,601
72,737,660
Nothing execute when using Vector in C++ with VSCode
The problem I have a problem with Vector in C++. When I try to do basic things with them, my program "doesn't works" anymore. What I tried Searching on Stack Overflow but didn't find something relevant. But I don't know a lot on this topic so I'm kind of stuck with it. Some code: Example: #include <iostream> #include <...
The command g++ -o -Wall main.cpp will create an executable file called -Wall. Unless that's the program you're trying to run, it's not going to work. Instead you would need something like g++ -o program -Wall main.cpp and then run program. Both of your examples do the right thing in that case.
72,737,873
72,759,302
Include and access multiple .so files and headers in one project using cmake
I have a simple foobar project which has a directory layout as follows: . ├── CMakeLists.txt └── src ├── CMakeLists.txt ├── Foo │ ├── CMakeLists.txt │ ├── foo.cpp │ └── foo.h └── Bar ├── CMakeLists.txt ├── bar.cpp └── bar.h Where Foo is standalone but Bar depends o...
The key concept here is property visibility. There are two types in CMake: PRIVATE: the property affects the target being built. INTERFACE: the property affects targets that link to this one directly, or transitively through target_link_libraries(... INTERFACE ...). The PUBLIC visibility is simply a shorthand for bot...
72,737,998
72,738,038
Int and Float arrays give wrong results after adding numbers using loops
Doing some simple exercies with C++ and I'm stuck... When my sum[t] array is declared as integer or float it sometimes outputs at the end some crazy values like for example 4239023 or -3.17802e+30 (despite the fact that I add only small numbers from range <-100; 300>). When I change it for double it works correctly. Wh...
You should initialize your array of sums to zeroes after you receive the value of t. You could do it like this: for (int i=0; i<t; i++) { sum[i] = 0; }
72,738,434
72,741,371
How to develop ue4 plugins to simulate the viewpoint in unity 3D?
Unity 3d has two viewpoints, one is game and another isscene. when you move objects in scene you can see changes happened in game in the same time. while the reverse is true. But UE4 doesn't have this function. So I wonder if I can develop a plugin for UE4 to achieve that? does anyone have a clue? enter image descripti...
Unreal 4: Go to Window -> Viewport 2. Drag the window somewhere and you will have 2 viewports: Press play, only one viewport will display the "gameview" and the other remains as "sceneview" - Moving stuff in the 2nd Viewport will not update the game! But I found this plugin: https://github.com/jackknobel/GameViewportS...
72,738,517
72,738,787
List initialization rules
I want to initialize std::vector<char> with count and value. This works: int n = 100; std::vector<char> v(n, 0); However, list initialization std::vector<char> v{n, char(0)}; gives me: warning: narrowing conversion of ‘n’ from ‘int’ to ‘char’. Is there a way to use list initialization syntax but avoid initializer_lis...
Unfortunately, no. When you're to list-initialize a std::vector, it'll first try to use the constructor with the std::initializer_list parameter. Other constructors will be considered only if there's no suitable match. Quoted from cppref All constructors that take std::initializer_list as the only argument, or as the...
72,738,654
72,738,723
C++ issue with conversion of std::string to std::wstring - Windows vs Linux
I'm trying to convert the string "pokémon" from std::string to std::wstring using std::wstring wsTmp(str.begin(), str.end()); This works on Windows, but on Linux it returns "pok\xffffffc3\xffffffa9mon" How can I make it work on Linux?
This worked for me on POSIX. #include <codecvt> #include <string> #include <locale> int main() { std::string a = "pokémon"; std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> cv; std::wstring wide = cv.from_bytes(a); return 0; } The wstring holds the correct string at the end. Important ...
72,738,824
72,738,993
Error trying to remove duplicate element from sorted Linked List
Why is my code giving a segmentation fault? The code runs perfectly for some test cases, but after a few it starts giving a segmentation fault Node *remove(Node *curr){ Node *temp=curr; while(curr->data==curr->next->data){ curr=curr->next; } temp->next=curr->next; delete(curr); return te...
You seem to be crossing purpose with these functions, and you're note retaining your proper target for your potentially updated duplicate consolidation. I'm gonna change the name to removeNode for several reasons, one of which is to avoid confusing it with std::remove that wouldn't be a problem if you hadn't inadvisabl...
72,738,831
72,739,386
how to change editcontrol with function?
hello guys I was plc programmer just trying to start C++ programmer I am trying to convert to this code to function m_file.Open(posText[7], CStdioFile::modeRead); m_file.ReadString(posValue[7]); UpdateData(TRUE); dlg.s_PostionZ2 = posValue[7]; UpdateData(FALSE); m_file.Close(); and this my function but it didn't work ...
what I am trying to do is just open a file and save to value and change location value You are passing in the function's output parameters by value, so they make copies of the caller's values. Any changes the function makes to the parameters is done to the copies and not reflected back to the caller. To do what you w...
72,740,042
72,743,941
exception error in vio_ssl_write(Vio*, const uchar*, size_t) in openssl
I have a decryption method which decrypts data using private key: auto decrypt_private(const unsigned char* data,size_t data_len, unsigned char* decrypted_data)-> int { std::string pr_key_name="mykey.pem"; std::string keypass = "pass"; char * keypass_byte= const_cast<char*>( keypass.c_str() ); //open the private key...
Adding ERR_clear_error() solved the problem: if(decrypted_data_size==-1){ ERR_clear_error(); delete[] decrypted_data; delete[] encrypted_data_byte; std::cout<<"decryption faild"; return 1; }
72,740,077
72,740,250
How to store text in wchar_t pointer parameter
I want to dll export some functions from cpp to dart and in order to do this I need to create a function with a pointer parameter where I will send text. But after many searches I found no solution that works. My question is: How to create a function with a wchar_t* parameter, and fill that variable with text? I have n...
sizeof(output) will return the number of bytes the array is. On Windows this will be 2000 instead of 1000 since each wchar_t is 2 bytes long. But the the value passed to the wcscpy_s is the number of wide characters that your array can hold. Your array can hold 1000 wchar_t's. But your are actually telling wcscpy_s th...
72,740,619
72,740,837
gcc problem with std::optional and packed struct member
I need to use a packed struct for parsing incoming data. I also have an std::optional value that I want to assign the value of one of the struct members. However, it fails. I think I understand the problem, basically making a reference to a variable that is not aligned with the memory width can be a bad thing. The code...
This is a problem of how clang and gcc assume the ARM cpu is configured. ARM cpus have a bit that says whether unaligned access should cause a processor trap or be handled by the cpu using slower access methods transparently. Clang defaults to the CPU allowing unaligned access while gcc defaults to the cpu trapping una...
72,740,626
72,741,155
64 bit equivalent of "GetModuleHandleA" need
I need to extent the compatibility of my application to 64 bit exe. __int64 GetGameFunctionAddress(std::string GameFileExe, std::string Address) { // Get integer value address of the original function hook #if defined(_WIN64) /// code to emulate GetModuleHandleA on 64 executible #else ...
GetModuleHandleW returns a value of type HMODULE (which is the same as HINSTANCE, aka HANDLE, aka PVOID, aka void*). In other words: It returns a pointer sized value. Pointer sized values are 32 bits wide in 32-bit processes, and 64 bits wide in 64-bit processes. Either way you get the address of the module base addres...
72,740,880
72,741,020
How to copy all the shared conan libraries into the build folder?
I have custom conan packages that output c++ shared libraries. (dylib or dll) Whenever I build my CMake project I would like all these shared libraries to be copied to the directory where the executable is. How can I achieve this?
You need to use the imports method of a conanfile.txt or conanfile.py that you use in your CMake project. Here the documentation: https://docs.conan.io/en/latest/reference/conanfile/methods.html#imports With aconanfile.py it look like this def imports(self): self.copy("*.dll", "", "bin") self.copy("*.dylib", "", ...
72,741,650
72,741,931
C++ Errors C2672 and C2893 when I use mutex in C++
When I use mutual parameter,'some mutex',in demo of shared data in multi-threading of C++,the two errors occur,and their codes are C2672: 'invoke': no matching overloaded function found shared_data C2893: Failed to specialize function template 'unknown-type std::invoke(_Callable &&) noexcept(<expr>)' Then I looked the...
My comment written out as a program : #include <cassert> #include <list> #include <mutex> #include <algorithm> #include <future> // avoid global variable, group related functions in a class //std::list<int> some_list; //std::mutex some_mutex; class my_async_list final { public: void add(const int new_value) // n...
72,741,750
72,741,811
Why is shared_ptr returning an empty list?
I am working with Xerces-c (version 3.2) and I have this function that wraps around the XMLString::transcode method. XMLCh* class_name::transcode(const std::string text) { auto returned = std::shared_ptr<XMLCh>(XMLString::transcode(text.c_str()), class_name::releaseXMLCh); return returned.get(); } (XMLCh is a char...
Think about it: you create a local std::shared_ptr. You get the (raw) pointer to the internal object. The local std::shared_ptr goes out of scope and is destructed. How many std::shared_ptrs will there be pointing to the internal object? None. So it's also destructed. Thus, this will not work this way. You are return...
72,741,755
72,742,071
insert element at bottom of stack
I am doing the Insert at Bottom of the stack question. This code is perfectly working in the CodeStudio but it is not giving the correct expected output in Visual studio code. why it is not displaying all the elements of the stack # include <iostream> # include <stack> # include <vector> # include <string> using namesp...
The problem is how you print the elements: for(int i=0; i<ans.size(); i++){ cout<<ans.top()<<" "; ans.pop(); } Due to calling ans.pop() ans.size() will decrease by one every iteration. At the same time i will increase by one every iteration. Basically you iterate twice as fast as intended. A better loop would ...
72,742,121
72,742,394
Why is the return value incorrect with optimisation flags on?
I am (for myself only) practicing c++ and trying to "re-code" c# properties into it. I do know it is useless (I mean, I will not use it) however, I just wanted to try to see if this was possible. For some reasons, with the following code, under the latest clang / gcc version, it does not yeld the correct result under e...
Your problem is this part: using getType = std::function<const T&(void)>; in combination with get{[this] () { return internal; }}. The lambda does not return the internal as a reference here, so a copy of internal is returned, and - here I don't know how std::function is implemented - std::function has to hold a copy o...
72,742,159
72,773,062
BGFX shader compilation using shaderc
I'm trying to compile the following shader from this tutorial: $input a_position, a_color0 $output v_color0 #include <bgfx_shader.sh> void main() { gl_Position = mul(u_modelViewProj, vec4(a_position, 1.0) ); v_color0 = a_color0; } I am working on windows so I modified the command from the tutorial to target ...
Comments in varying.def.sc aren't parsed by shaderc correctly, you'll unfortunately have to remove them.
72,742,207
72,745,933
insert dtype in std::map
I want to do a map that takes a pair of pybind11::dtype and int and maps it into an OpenCV format: static std::map<std::pair<pybind11::dtype, int>, int> ocv_types; So I inserted all combinations but there seems to be a problem when adding int32_t and float_t: ocv_types.insert(std::make_pair(std::make_pair(pybind1...
As you noted pybind11::dtype do not have any particular order. So IMO best approach is to use std::unordered_map and provide respective hashes. pybind11 already has some hash function, so it is needed to adopt it for std::hash. Here is test I've wrote (using Catch2) and it passes on my machine: main.cpp: #include "catc...
72,742,242
72,756,878
How does atomic seq_cst memory order actually work?
For example, there are shared variables. int val; Cls obj; An atomic bool variable acts as a data indicator. std::atomic_bool flag = false; Thread 1 only set these variables. while (flag == true) { /* Sleep */ } val = ...; obj = ...; flag = true; /* Set flag to true after setting shared variables. */ Thread 2 only...
Yes, the code is fine, and as ALX23z says, it would still be fine if all the loads of flag were std::memory_order_acquire and all the stores were std::memory_order_release. The extra semantics that std::memory_order_seq_cst provides are only relevant to observing the ordering between loads and stores to two or more d...
72,744,346
72,744,451
Are 'const foo**' and 'foo** const' the same thing?
I know that for a type foo, the function declaration for bar void bar(const foo*) and void bar(foo* const) are the same thing. But that about double indirection? That is, are void bar(const foo**) and void bar(foo** const) also the same thing? If not, then what do I need to do to void bar(foo** const) to put the cons...
Case 1 Here we consider void bar(const foo*); #1 void bar(foo* const) #2 In #1 we've a pointer to a const foo while in #2 we've a const pointer to a nonconst foo. You could use std::is_same to confirm that they're different: std::cout << std::is_same<const foo*, foo* const>::value << ' '; //false Case 2 Here we co...
72,744,558
72,744,957
c++11 promise object gets invalid, but its future object neither returns value nor throw exception
I've got this test code to see, if a promise object is out of lifecycle, what happen to its future object: #include <chrono> #include <future> #include <iostream> #include <thread> using namespace std; void getValue(future<int>& future) { cout << "sub process 1 \n"; try { cout << "sub process 2 \n"; ...
Your problem is not about std::promise or std::future behavior. You simply cause a data race (and consequently undefined behavior) by passing the flocal object by-reference to the thread, accessing it in the thread, but also destroying it in the main thread without any synchronization. This doesn't work no matter what ...
72,745,018
72,745,251
Problem with memoization for recursive algorithm
I am calculating the least amounts of 3s and 5s that sum up to N. I used memoization and recursive algorithm. The problem is, when I run the program and input 11, temp3 = calculate(8) returns 1, when it should clearly return 2. I have checked that before calculate(8) is called, arr[8] = 2 already. #include <iostream> ...
You are operating on global variables! Several recursive calls use the same variables and it happens that the call temp5 = calculate(N-5); overwrites the temp3 value that has previously been set by the call temp3 = calculate(N-3);! Solution: Do not use global variables! int temp3 = calculate(N-3); int temp5 = calculate...
72,745,318
72,748,767
Cmake using git-submodule inside a shared library
I try to add the library spdlog to a dll (.so file). The spdlog is just a git submodule from the spdlog library. Looking at the documentation, it's recommended to use it as a static library. So i think i have a problem trying to compile it inside a .so file. To get a clear view of what i'm doing, here is a pic of my sy...
Thanks to fabian in the comments, I add set(CMAKE_POSITION_INDEPENDENT_CODE 1) Just before adding the spdlog subdirectory and it just works fine.
72,745,386
72,771,141
Potential memory leak if a tuple of a unique pointer is captured in lambda
clang-tidy and scan-build warn about a potential memory leak in this code: #include <tuple> #include <memory> int main() { auto lambda = [tuple = std::make_tuple(std::make_unique<int>(42))] {}; } $ clang-tidy main.cpp -checks="clang*" 1 warning generated. /foo/main.cpp:7:1: warning: Potential leak of memory point...
An unsolved bug in clang-tidy: https://github.com/llvm/llvm-project/issues/55219 It doesn't have anything to do with tuples or smart pointers as seen in the simplified reproduction in this comment.
72,746,726
72,747,076
Function which takes different enum classes types as input, how?
I am facing the following problem. Supposing I have two (or more) enum classes like these: enum class CURSOR { ON, OFF }; enum class ANSI { ON, OFF }; I am trying to implement a (template) function called OPTION able to do something like this: OPTION( CURSOR::ON ); OPTION( ANSI::ON ); I tried implementing it in this ...
I agree with 273K and templatetypedef about using overloads instead. However, if you have your heart set on having a template with the case handling logic all in one place, you can do it this way: #include <iostream> #include <type_traits> using std::cout; enum class CURSOR { ON, OFF }; enum class ANSI { ON, OFF }; ...
72,747,487
72,861,795
How do I make the `std::ios_base::copyfmt_event` happen in my tests?
I wrote a set of functions to print out an address in my libaddr library (see addr.h header). I am easily able to test the erase_event by changing one of my format flags: std::cout << addr::setaddrsep("\n") << addresses; I do not care about the imbue_event (the locale has no effect on IP addresses). What I'm wondering...
From https://en.cppreference.com/w/cpp/io/basic_ios/copyfmt : #include <iostream> #include <fstream> int main() { std::ofstream out; out.copyfmt(std::cout); // copy everything except rdstate and rdbuf out.clear(std::cout.rdstate()); // copy rdstate out.basic_ios<char>::rdbuf(std::cout.rdbuf()); // s...
72,747,807
72,747,979
How to CRC check a whole structure (without padding)
I have a structure which contains memory for an EEPROM: #pragma pack(push,1) struct EEPROM_Memory { char Device_ID[8]; uint8_t Version_No; otherRandomVariables... }; #pragma pack(pop) I then create an instance, populate the struct and calculate it's CRC using: CRC32::calculate(reinterpret_cast<uint8_t*>(&(memory...
Pretty sure the pack is working as it should and you are using it wrong. Note that pack is not recursive. So if your any of your otherRandomVariables is a struct then that struct may contain padding. What you should do is static_assert the size of the struct. Then you know if it has the expected size or some padding. I...
72,747,867
72,748,094
using namespace std causes boost pointer cast to trigger ADL in c++17 standard
I have a simple code with inheritance and shared_ptr from boost library. With standard c++20, the code compiles fine. The function calls to static_pointer_cast and dynamic_pointer_cast compiles without prepended boost:: namespacing -- these function calls work because of ADL (Argument Dependent Lookup). But with standa...
When the compiler sees a < after an identifier in an expression (such as in static_pointer_cast<Animal>(dp)) it needs to figure out whether < refers to the relational less operator or whether it is the start of a template argument list. If a template is found by usual unqualified name lookup (not ADL), then the latter ...
72,749,196
72,749,536
What is the best way to use printf in output?
This is code for a project I have recently almost completed. The code takes a gross value and then does some math to get a bunch of new values. My final instruction is to output the console output into a file. I need both a console output and a file output. My issue is I have been trying for almost a day to figure out ...
Side note: If you are coding in C++ then you should use the newer functionalities such as cout or fstream instead of printf of fprintf Now, coming to your question: What you are probably looking for is fprintf() Here's a snippet using the function that I just mentioned above: FILE * fp = fopen ("file.txt", "w+"); ...
72,749,220
72,749,634
create a class in C++
In C++ suppose I defined a class named Player without a default constructor. When I creating a class instance in the main function: Player John; The class will be created and I can see it in the debugger but the Player Adam() the class will not be created Why the class will not be created in Player Adam(); isn't Adam()...
I think your problem is that you are not really creating the second object. I put your code on compiler explorer here, where you can see the compilation warnings: <source>: In function 'int main()': <source>:16:17: warning: empty parentheses were disambiguated as a function declaration [-Wvexing-parse] 16 | Pla...
72,749,665
72,752,706
C++ abstract method, different parameters in different inheritances
I have a base class from which several classes should inherit. The base class is supposed to be a simple interface, which one inherits for a easy implementation/ for passing data into a library. However, the parameters of the overridden method vary depending on the implementation (inheritance). In my concrete case, a c...
C-style variadic functions should be avoided in C++. Better would be to use variadic template functions, but unfortunately that doesn't really work for virtual functions, see this post for an explanation why. @AdrianMole and @user17732522 hinted at the right answer: try to find a way to pass a list of things as a singl...
72,749,832
72,749,903
In the example of std::atomic<T>::exchange, why the count of times is not 25?
The example I talked about is this one on cppreference.com. The code snippet is pasted below. int main(){ const std::size_t ThreadNumber = 5; const int Sum = 5; std::atomic<int> atom{0}; std::atomic<int> counter{0}; // lambda as thread proc auto lambda = [&](const int id){ for (int nex...
Consider one of the possible executions: Lets say one of the threads finishes the loop before other threads start. This gives you atom == 4. The next thread to enter the loop will get current == 4 and will exit the loop after the first iteration. This way the second thread increments current once instead of 5 times lik...
72,749,955
72,753,193
Unable to compile the example for Eigen SVD
I am trying to compile the example provided for Eigen::JacobiSVD and I am getting the following error, /usr/local/include/eigen3/Eigen/src/SVD/JacobiSVD.h: In instantiation of ‘Eigen::JacobiSVD<MatrixType, QRPreconditioner>& Eigen::JacobiSVD<MatrixType, QRPreconditioner>::compute(const MatrixType&, unsigned int) [with ...
This looks very much like a bug. I looked at the code and there is no way it can work. I'll file a bug report. As a workaround, this should work even though it is marked as deprecated: JacobiSVD<MatrixXf> svd; svd.compute(m, ComputeThinU | ComputeThinV); The underlying issue is that during template-specialization, the...
72,750,175
72,750,255
ARM64 64 bit load/store data race
According to this, a 64 bit load/store is considered to be an atomic access on arm64. Given this, is the following program still considered to have a data race (and thus can exhibit UB) when compiled for arm64 (ignore ordering with respect to other memory accesses) uint64_t x; // Thread 1 void f() { uint64_t a = x; ...
Whether or not an access is a data race in the sense of the C++ language standard is independent of the underlying hardware. The language has its own memory model and even if a straight-forward compilation to the target architecture would be free of problems, the compiler may still optimize based on the assumption that...
72,750,692
72,750,706
Why is the value of the variable not increasing after sizeof(++)?
The value i is 1, but why is i still 1 after sizeof(i++)? I only know sizeof is an operator. int main() { int i = 1; sizeof(i++); std::cout << i << std::endl; // 1 }
sizeof does not evaluate its operand. It determines the operand's type and returns its size. It is not necessary to evaluate the operand in order to determine it's size. This is actually one of the fundamental core principles of C++: the types of all objects -- and by consequence of all expressions -- is known at compi...
72,751,128
72,758,206
Using SFINAE to check if member exists in class based on a template
The example here shows how we can use TMP to have the compiler elide functions based on whether a member exists for a given type. I want to write a metafunction that works for classes based on templates. Compilation should succeed if a class based on a template is provided in the function call that has the desired memb...
The template parameters of the template template parameter can not be used in the body. template <typename T, typename = void> struct has_psl : std::false_type {}; template <template <typename> typename EntryType, typename KeyType> struct has_psl<EntryType<KeyType>, std::void_t<decltype(EntryType<KeyType>::psl)>> : st...
72,752,046
72,752,574
Runtime polymorphism in C++ using data members
I was studying OOP from here. It says that runtime polymorphism is possible in C++ using data members. Now,consider this code:- #include <iostream> using namespace std; class Animal { // base class declaration. public: string color = "Black"; }; class Do...
If this was runtime polymorphism you could write a function: void foo(Animal& a) { std::cout << a.color << "\n"; } And it would print the respective color of the object based on the dynamic type of the parameter. However, there is no such thing as "Runtime-polymorphism based on member variables" in C++. The tutori...
72,752,156
72,752,175
c++11 is it safe to return an initializer_list value?
I've this simple function: initializer_list<int> f(){return {1,2,3};} g++ gives a warning saying: warning: returning temporary initializer_list does not extend the lifetime of the underlying array [-Winit-list-lifetime] Is there any risk to return an {1, 2, 3}? Thanks for explanations!
An initializer_list behaves like a reference extending lifetime of a temporary (the temporary being the array). Lifetime extension doesn't apply when returning references, so it doesn't apply here too. The compiler is right, the returned list is always dangling.
72,752,296
72,752,455
SDL_SetWindowHitTest - callback & callback_data? (SDL 2.0.5)
Could someone please help me to understand what these two parameters are, and how to interact with/utilize them? The Wiki says that callback is a function - itself - what should the call of it be like and what should it be returning/doing? Current Purpose: to Move a Borderless Window (via mouse click and drag) Alterna...
Here's how SDL_HitTest (the callback type) is defined: /** * Callback used for hit-testing. * * \param win the SDL_Window where hit-testing was set on * \param area an SDL_Point which should be hit-tested * \param data what was passed as `callback_data` to SDL_SetWindowHitTest() * \return an SDL_HitTestResult val...
72,752,502
72,752,802
Array doesn't print correct values beyond a certain limit of indices
The following code gives a very wrong and random output for inputs greater than 5,5 (respective values of m and n wrt the code below). Why is it so? What might be the fix to this? #include <bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--) { int m,n; cin>>m>>n...
If you compile this withg warnings enabled you get: <source>:18:15: warning: equality comparison result unused [-Wunused-comparison] a[0][0] == 1; ~~~~~~~~^~~~ <source>:18:15: note: use '=' to turn this equality comparison into an assignment a[0][0] == 1; ^~ = 1 warning gen...
72,752,841
72,752,934
How to efficiently calculate the symmetric force matrix (Newton's 3rd law)?
Intro For the N-body simulation I need to calculate the total received force Fi for each body it receives from the other bodies. This is an O(n^2) problem, because for each body the pairwise total force must be calculated. Because of the Newton's 3rd axiom fi,j = -fi,j we can reduce the number of force calculations by ...
The simple solution is to have the inner loop start from i + 1 instead of from 0: for (size_t i = 0; i < num_bodies; ++i) { glm::vec3 received_total_force(0.0); for (size_t j = i + 1; j < num_bodies; ++j) { glm::vec3 distance_squared = glm::distance2(bodies[i].getCurrentPosition(), bodies[j].getCurrentP...
72,753,084
72,753,174
Values subtraction in the time calculation
Having such a bit of code: DWORD time1 = 0xFFFFFFFC; DWORD time2 = 0x0000000B; //11 dec DWORD time3 = 0x0000000D; //13 dec DWORD time4 = 0x0000000F; //15 dec swprintf_s(g_msgbuf, L"delta1: %i, %u\n", time2 - time1, time2 - time1); OutputDebugString(g_msgbuf); swprintf_s(g_msgbuf, L"delta2: %i, %u\n", time3 - time1, t...
Unsigned arithmetic is performed modulo the max value the type can hold plus one. Therefore 0x0000000B - 0xFFFFFFFC with 4 byte unsigned types such as DWORD yields the same result as 0x0000000B - (0xFFFFFFFC + 4 - 4) or 0x0000000B + 4 - (0xFFFFFFFC + 4) or (using the fact that the brackets are 0 modulo the max value...
72,753,113
72,753,151
Is it ok to put the main loop of a program in the constructor of a class?
I am making a Bomberman game, and it needs a "main loop" where the game updates constantly. Here's basically what I did : class BomberMan { public: BomberMan() { Init_BomberMan(); while (RayLib::ShouldWindowClose()) { // game updates things } ...
It's pretty bad to do so. The constructor is supposed to initialize the class. So having a function Init_BomberMan shows that you don't understand what a constructor is for. That function should be the constructor and probably nothing else. And then you should have a function that runs your game, lets call that run as ...
72,753,182
72,755,299
SOCKS5 responds with no BND.ADDR nor BND.PORT?
Although this looks like a bug, some developers argue how it complies perfectly with the RFC. I wrote a simple C++ program on Linux which connects to a HTTP web-page and reads its contents over Tor. I start a tor service using this command: tor --ignore-missing-torrc -f / --SocksPort auto --DataDirectory $HOME/tren/tor...
Your SOCKS5 request is perfectly fine, and the proxy is replying back that it successfully connected to www.icanhazip.com:80, so just start exchanging your HTTP data as needed over your existing connection to the proxy. The proxy's reply is simply telling you that it bound itself to 0.0.0.0:0 (or maybe it is choosing n...