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
74,106,875
74,134,834
Adding ApproxMVBB into Android Studio
I'm trying to find the minimum volume bounding box given a set of point clouds in Android. This repo seem to contain the solution: https://github.com/gabyx/ApproxMVBB But I'm having trouble installing it into my Android Project. I've tried: using Cmake to build eigen (not approxMVBB yet) -> it fail at build time. using top level Cmake to build both eigen and approxMVBB in Android -> cant seem to find Eigen3Config.cmake built both of these two libs on my computer (Windows 10) using minGW64 -> created a dll and a dll.a file -> which seem to be incompatible with Android. copy {eigen_dir}/Eigen directly into scr/main/cpp, then hardcoded ApproxMVBB CMakeList with "include_directories(Eigen)" -> android build seem to have issue with Ninja. I'm currently thinking that ApproxMVBB is simply incompatible with Android devices, but I'm not so sure. Any help or confirmation would be highly appriciated.
Nvm, I got frustrated so I wrote a MVBB for Java. The code is here: https://github.com/ginofft/ARCoreDemo/blob/master/MVBB_Java/src/main/java/scr/MVBB.java
74,106,896
74,107,037
typeid(*this).name() returns null pointer on delegated constructor of std::exception subclass
I found a strange behavior running this small snippet of code compiled with clang: #include <iostream> #include <exception> #include <typeinfo> struct Foo : public std::exception { std::string myString; Foo(const std::string& str) : myString(str) {} Foo() : Foo(typeid(*this).name()) {} }; int main() { Foo f; std::cout << f.myString; } The instruction typeid(*this).name() called inside the delegated constructor returns a nullptr that causes a segmentation fault. During the delegated constructor call std::exception base class is not yet initialized and this seems the cause of this behavior. I'm wondering if this code is ill-formed for some reason, or this behavior is expected. I cannot reproduce this bug with g++, where the code runs fine. It also occurs only if the base class is std::exception, in any other case it works fine even on clang.
This has undefined behavior. typeid is allowed to be applied to the object under construction in the constructor, also the member initializer list, but only after construction of all base class subobjects has completed. See [class.base.init]/16. If typeid(*this) was used after the base classes have been constructed, then [class.cdtor]/5 would describe the behavior of typeid in this specific situation. (It would return the type_info corresponding to Foo irregardless of whether Foo is the most-derived type.) I think this is only supposed to apply though if *this has polymorphic type, i.e. Foo has a (inherited) virtual member function (std::exception::what and std::exception::~exception in your case). The current wording doesn't seem to clearly separate this, but for non-polymorphic types the expression shouldn't even be evaluated, so it can't matter that *this refers to the object under construction. There are related open CWG issues, e.g. CWG issue 1517.
74,108,118
74,108,159
std::vector, member access operator and EXC_BAD_ACCESS
Why can I execute an operator& from a (*iterator), but can not make copy of value (*iterator) ? std::vector<int> v; // yes, container is empty for (int i = 0; i < 10; ++i) { auto it = v.begin(); std::cout << &*(it) << std::endl; // 0 <- why not EXC_BAD_ACCESS? auto value = *(it); // EXC_BAD_ACCESS auto address = &value; }
v is empty, hence v.begin() == v.end() and dereferencing it is undefined.
74,108,154
74,108,836
Running code in one thread is slower than running the code in main thread
I'm testing running double calculations in a thread and I got this strange result. Running the calculations in the main thread takes almost half the time than running it in a separate thread and calling join in the main thread. If it's a single thread there shouldn't be a big difference from just running the function. Am I doing something wrong? The cpu is Intel Xeon E-2136 limited at 4.1GHz to have the same boost frequency in independent of how many cores are running. #include <cstdio> #include <stdexcept> #include <thread> #include <future> #include <malloc.h> #include <time.h> #define TEST_ITERATIONS 1000*1000*1000 void *testNN(void *dummy) { volatile double x; for (int i = 0; i < TEST_ITERATIONS; ++i) { x = rand(); x *= rand(); } return nullptr; } int main(){ time_t start = time(nullptr); { // for future to join thread testNN(nullptr); // 12s // pthread_t thread_id; // pthread_create(&thread_id, NULL, testNN, nullptr); // pthread_join(thread_id, NULL); //27s std::future<void *> f[12]; // f[0] = std::async(std::launch::async, testNN, nullptr); // 27s // for multithreaded testing: // f[1] = std::async(std::launch::async, testNN, nullptr); // f[2] = std::async(std::launch::async, testNN, nullptr); // f[3] = std::async(std::launch::async, testNN, nullptr); // f[4] = std::async(std::launch::async, testNN, nullptr); // f[5] = std::async(std::launch::async, testNN, nullptr); // f[6] = std::async(std::launch::async, testNN, nullptr); // f[7] = std::async(std::launch::async, testNN, nullptr); // f[8] = std::async(std::launch::async, testNN, nullptr); // f[9] = std::async(std::launch::async, testNN, nullptr); // f[10] = std::async(std::launch::async, testNN, nullptr); // f[11] = std::async(std::launch::async, testNN, nullptr); } time_t runTime = time(nullptr); runTime -= start; printf("calc done in %lds (%ld calc/s)\n", runTime, TEST_ITERATIONS / runTime); } I compile with # g++ -std=c++11 test.cpp -o test -lpthread and results for function call, pthread and std::async respectively: # time ./test calc done in 12s (83333333 calc/s) real 0m12.073s user 0m12.070s sys 0m0.003s # time ./test calc done in 27s (37037037 calc/s) real 0m26.741s user 0m26.738s sys 0m0.004s # time ./test calc done in 27s (37037037 calc/s) real 0m26.788s user 0m26.785s sys 0m0.003s P.S. I'm still not sure if I want to use C++11. I used C++11 just to test if there is going to be a difference between plain phread and std::async. Update: here is an easier to test version with less chance for mistake: https://pastecode.io/s/ov4ifgy5
Thanks to @AndreasWenzel I found out rand() is causing the slow down. In theory it shouldn't be a problem when only one thread is running (or at least no other thread is calling rand). Replacing rand() with rand_r() fixes the problem and even brings down the time to 8s for the same amount of work. Here is the test function: void *testNN(void *dummy) { volatile double x; unsigned int seed = (unsigned int) time(nullptr); for (long i = 0; i < TEST_ITERATIONS; ++i) { x = rand_r(&seed); x *= rand_r(&seed); } return nullptr; } I know seeding like this is not ideal - starting 12 threads will most likely seed all the threads with the same number, but that's just a test. I'll most likely have more complex seed function.
74,108,282
74,148,359
Scope of <Plug>(coc-references) don't search on entire project folder
Using coc.vim feature (coc-references) on the name of classA or any other one, it seems to search and find references only on local file ClassA.cpp, not on entire project folders' sources. ProjecT-Root SubfolderA/classA.cpp SubfolderB/classB.cpp classeC.cpp calling new classA The command (coc-references) report me only classA.cpp occurrences. I would like all references reported on entire project. If i use coc-references-used, it's the same. Thank you Nicolas
It's language server's issue, coc-references requests textDocument/references to language server, LS returns results and coc.nvim display them.
74,108,349
74,108,614
Why std::unordered_set iterator not invalidate after rehash()?
from documentation: Iterator invalidation: rehash | Always I'm trying to invalidate a iterator. But it stay valid even after a manual call rehash(). Test sample: std::unordered_set<int> set; set.insert(10); auto it = set.begin(); const int& ref = *it; for(int i = 0; i < 10; ++i) { set.insert(i); std::cout << *it << " | " << ref << " : " << set.load_factor() << " / " << set.max_load_factor() << std::endl; } set.rehash(100); std::cout << *it << " | " << ref << " : " << set.load_factor() << " / " << set.max_load_factor() << std::endl; stdout: 10 | 10 : 1 / 1 (rehash) 10 | 10 : 0.6 / 1 10 | 10 : 0.8 / 1 10 | 10 : 1 / 1 (rehash) 10 | 10 : 0.545455 / 1 10 | 10 : 0.636364 / 1 10 | 10 : 0.727273 / 1 10 | 10 : 0.818182 / 1 10 | 10 : 0.909091 / 1 10 | 10 : 1 / 1 10 | 10 : 0.108911 / 1
I'm trying to invalidate a iterator. Calling rehash does invalidate iterators. But it stay valid even after a manual call rehash(). Not it does not stay valid. What you do not spell out explicitly is: You get expected output hence conclude that the iterator is still valid. You cannot test if an iterator is valid. Dereferencing an invalid iterator is undefined. The result can be anything (including a seemingly correct result). Colloquially speaking, "invalid" means "no guarantee that it works", it does not mean "guaranteed to fail". This is the case in general with undefined behavior. You cannot conclude from correct looking output that the code is correct. A somewhat silly but imho somewhat useful analogy is a broken calculator. It has * and + swapped. You ask for the result of 2+2 and get 4. Looks correct, but from that you cannot conclude that the calculator is not broken.
74,109,103
74,110,248
KeyPressEvent works crookedly in QLable
I have a class that inherits QLabel. And it has keyPressEvent called, only after clicking on Tab enum ElemntType { tBall, tWall, tGate, tPacman, tGhost, tWeakGhost, tPowerBall }; enum Dir { Left, Right, Up, Down, Stop }; class PacMan : public QLabel { Q_OBJECT public: explicit PacMan(); ~PacMan() = default; private: QMovie anim; Dir dir; ElementType type; int x, y; private: void keyPressEvent(QKeyEvent* event); }; and cpp file with it PacMan::PacMan() : QLabel(), type(type), dir(Stop) { setFocus(); anim.setFileName("../Texture/startPacman.png"); anim.start(); setMovie(&anim); setFixedSize(20, 20); x = pos().x(); y = pos().y(); } void PacMan::keyPressEvent(QKeyEvent* event) { switch (event->nativeVirtualKey()) { case Qt::Key_A: dir = Left; anim.stop(); anim.setFileName("../Texture/lPacman.gif"); anim.start(); move(--x, y); break; case Qt::Key_D: dir = Right; anim.stop(); anim.setFileName("../Texture/rPacman.gif"); anim.start(); move(++x, y); break; } } When I try to press keys nothing happens (keyPressEvent is not called at all), but if I press Tab then keyPressEvent will work fine. Why is this happening and how to fix it? main.cpp int main(int argc, char* argv[]) { QApplication app(argc, argv); QGraphicsView view(new QGraphicsScene); PacMan* move = new PacMan(); move->setFocusPolicy(Qt::StrongFocus); view.scene()->addWidget(move); view.show(); return app.exec(); }
With Qt::StrongFocus, your widget is made focus-able using tab and mouse. However, it does not necessarily get the focus. One way to force it is to set Qt::NoFocus for all other widgets before setting your Qt::StrongFocus. It can be done with (taken from the answer to: How to set Focus on a specific widget): for (auto widget : findChildren<QWidget*>()) if (! qobject_cast<QOpenGlWidget*>(widget)) widget->setFocusPolicy(Qt::NoFocus);
74,109,142
74,109,324
Problem with multiple includes in VSCode / platformio
The issue occurs when I try to work with multiple files in VS Code / PlatformIO. So I built an example to show the problem: The linker (firmware.elf) says: 'multiple definition of 'variable';' var.h: #ifndef var_h #define var_h #pragma once #include <Arduino.h> int variable; void set_var(int number); #endif // var_h var.cpp #include "var.h" void set_var(int number){ variable = number; } main.cpp #include <Arduino.h> #include <SPI.h> #include "var.h" void setup() { Serial.begin(115200); } void loop() { Serial.print(variable); delay(2000); } platformio.ini [env:esp32dev] platform = espressif32 board = esp32dev framework = arduino I've already tried using either #pragma once or #ifndef ... exclusively, but it didn't work. Same error.
You seem to misunderstand how header guards (your #ifndef var_h and associated directives) work and also how declarations of 'external' variables work. The header guards (either the aforementioned or the #pragma once directive) will prevent multiple inclusion/processing of that file from any given, single translation unit (TU) but not from different TUs. So, for example, if one source file has multiple #include "var.h" lines – or if it also includes another header which itself has a #include "var.h" line – then those guards will prevent multiple inclusions. However, when you compile "var.cpp" and "main.cpp" (separately), the 'context' is reset for each one. Thus, each of those compilations will see the int variable; line, so causing multiple definitions. In your case, what you need to do is specify in the header that variable is an int but is defined elsewhere: extern int variable;. Then, in only one source file (most likely "var.cpp") provide the actual definition, with a line like int variable; (preferably, with an initial value, though: int variable = 0;).
74,109,309
74,109,615
Can we pass thread to parameterised constructor that accepts argument by rvalue reference?
I would like to pass std::thread temporary object directly to my ThreadGuard class but somehow that is not producing any output, however if I first create local std::thread variable and pass that to constructor then it is working fine. So my question is can't we pass temporary thread to function taking rvalue reference parameter ? #include <iostream> #include <thread> using namespace std; class ThreadGuard { private: std::thread& m_t; public: ThreadGuard(std::thread& t):m_t(t) { std::cout<<"By lvalue ref constructor "<<std::endl; } ThreadGuard(std::thread&& t):m_t(t) { std::cout<<"By rvalue ref constructor "<<std::endl; } ~ThreadGuard() { if(m_t.joinable()) { m_t.join(); } } }; void foo() { std::cout<<"Inside foo..."<<std::endl; } int main() { //This is working //std::thread th(foo); //ThreadGuard t1(th); //This is not giving any output ThreadGuard t(std::thread(foo)); return 0; }
What you have just come across is C++'s most vexing parse syntax. The compiler thinks that you have declared a function t which returns a ThreadGuard and takes an argument foo of type std::thread: ThreadGuard t(std::thread foo); A possible solution would be to use curly braces for initialization, as such: ThreadGuard t(std::thread{foo});
74,109,423
74,112,020
How to cast struct of std:array<char> to single std::array<char>
I'm packing messages to be send to another device. I'm using C++11. Usually the payload is a single ASCII encoded value, but this one command has a bit more parameters. I'm trying to pack the payload in a single array of chars. I'm looking for a clean solution, and I thought that the following (example) solution should work: Message foo(Parameters parameters) { struct __attribute__((__packed__)) ParameterPayload { std::array<char,2> a; std::array<char,2> b; std::array<char,2> c; std::array<char,4> d; }; // Actual struct has way more parameters ParameterPayload paramPayload; paramPayload.a = bar<2,10>(parameters.a); paramPayload.b = bar<2,10>(parameters.b); paramPayload.c = bar<2,10>(parameters.c); paramPayload.d = bar<4,16>(parameters.d); // This will not work, but I want something like this to work auto payload = reinterpreted_cast<std::array<char, sizeof(ParameterPayload)>(paramPayload); return baz<sizeof(ParameterPayload)>(payload); } template<size_t size, int base> std::array<char, size> bar(int input> { // ASCII encoding with a base (2, 10 or 16) } template<size_t payloadSize> Message baz(std::array<char, payloadSize> payload) { // Some packing computation } This is a rough example, but I think it will get the message across. How do I cast the struct to a single std:array<char, N>? Is it even possible? I'm trying not to do multiple std::copies instead, because that will cost more resources and will worsen readability. another solution I looked into is using const char* const payload = reinterpret_cast<const char* const>(&paramPayload); and going from there... I could do a single copy after that, but I'd like to avoid it.
That casting is pedantically UB (and even we don't have guaranty of exact size of std::array). I suggest to change to something like: Message foo(Parameters parameters) { std::array<char, 2+2+2+4> payload; // Actual struct has way more parameters int offset = 0; bar<2, 10>(parameters.a, payload.data() + offset, offset); bar<2, 10>(parameters.b, payload.data() + offset, offset); bar<2, 10>(parameters.c, payload.data() + offset, offset); bar<4, 16>(parameters.d, payload.data() + offset, offset); return baz(payload); } template<size_t size, int base> void bar(int input, char* out, int& offset) /* std::span<char, size> out (in C++20) */ { offset += size; // ASCII encoding with a base (2, 10 or 16) } template<size_t payloadSize> Message baz(std::array<char, payloadSize> payload) { // Some packing computation }
74,110,147
74,110,427
Finding the min value of a vector of int
I have a vector of integers something like this: vector<int>distances = {1,5,7,15}; And i would like to store the minimal value of those in a int variable like this: int varname = minValueOfDistances; Is there any function in c++ that does that? Or do I have to create one?
Yes! there is a builtin Function vector<int> distances = {1, 5, 7, 15}; cout << *min_element(distances.begin(), distances.end()); what does min_element needs? and what does it return? it needs a pointer of the beginning Range you wants to get the minimum element and the end of your range and what does it return? It returns a pointer where is this element exactly .. but we want the value of this element .. so we use * to get the value of it
74,110,661
74,121,539
How to disable intelllisense errors in vscode when using macros defined with -D flag?
I have a CMake file which defines PROJECT_PATH macro for my project with the -D flag. I want to be able to use that macro in code to access a file relative to that path, like this: auto file = open_file(std::string(PROJECT_PATH) + 'path/to/the/file.txt'); Is there any way to disable the intellisense error messages only for that particular macro? Edit: I have found a dirty solution which works for now: in the .vscode/settings.json I added: "C_Cpp.default.defines": [ "${default}", "PROJECT_DIR=\"\"" // dirty hack to disable intellisense errors ]
To let IntelliSense know about your macros, you must create the file c_cpp_properties.json in your .vscode folder. There you can specify your macros in the field "defines". However, this is not perfect because you have to do it twice, once in the build and once here. A better approach is to use "compileCommands", where you can set the path to file compile_command.json, where will be placed all macros from the build. CMake automatically generates this file if you turn it on with the CMAKE_EXPORT_COMPILE_COMMANDS definition. c_cpp_properties.json { "configurations": [ { "name": "Linux", "includePath": [ "${workspaceFolder}/**" ], // macro defined only for intelisense. It won't be used for build "defines": [ "MY_DEFINE=\"some_text\"" ], "compilerPath": "/usr/bin/g++", "cStandard": "c17", "cppStandard": "c++17", "intelliSenseMode": "linux-gcc-x86", // owerwrite inlucdes and defines with values used from build "compileCommands": "${workspaceFolder}/build/compile_commands.json", "browse": { "path": [ "${workspaceFolder}/**" ] } } ], "version": 4 } CMakeLists.txt cmake_minimum_required(VERSION 3.0.0) project(TestArea VERSION 0.1.0) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) add_compile_definitions(MY_DEFINE="some/path") add_executable(TestArea test.cpp)
74,110,853
74,400,412
How to check if Tensorflow is using the CPU with the C++ API?
I have a C++ program using Tensorflow 2 to run inferences of a convolutional neural network. The program runs on a server with a dedicated GPU and the expected behavior is the inference to run on the GPU. In case of a GPU failure, Tensorflow starts using the CPU instead of the GPU. Is there any way with the Tensorflow C++ API to check if Tensorflow is using the CPU? Is there any way with the C++ API to avoid Tensorflow switching to the CPU in case of GPU failure?
Finally I've solved it in the following way: bool DedicatedGPUAvailable(tensorflow::Session* session){ if (session != nullptr) { std::vector<tensorflow::DeviceAttributes> response; session->ListDevices(&response); // If a single device is found, we assume that it's the CPU. // You can check that name if you want to make sure that this is the case if (response.size() == 1) { std::cout << "No GPU found! Total available devices = 1" << std::endl; std::cout << "Available devices: " << std::endl; for (unsigned int i = 0; i < response.size(); ++i) { std::cout << i << " " << response[i].name() << std::endl; } return false; } } return true; }
74,112,138
74,120,752
Visual Studio debugger - How to jump to last iteration of a loop with a dynamic termination condition
I am looking for a way to jump to the last iteration of a loop with a dynamic termination condition. Consider the following model LoopManager loopManager(/* params */) for (; loopManager.MustKeepIterating() && loopManager.foo() /* && ... */; loopManager.Increment()) { /* ... */ loopManager.Update(); } In this scenario, I can't just loop until n-1 where n is the termination valued condition, because the termination condition is dynamic by depending on the body of the function. What would be interesting or elegant ways to jump the last iteration in this loop before it gets terminated, as to investigate the functions in the body, at that last iteration? I need to investigate the last iteration, but there are thousands of iterations in my case.
Your model needs to be modified to hit the break point: LoopManager loopManager(/* params */); auto var =loopManager.MustKeepIterating() && loopManager.foo() ; for (; var; loopManager.Increment())// add conitional break point this line. Expression e.g.: var== false { /* ... */ loopManager.Update(); var=loopManager.MustKeepIterating() && loopManager.foo() /* && ... */ }
74,114,244
74,114,310
Cannot insert a enum type into a map
I am a novice at C++, but I am trying to build a std::map that has an enum type as value, to avoid fussing with strings. I have created a minimum example below which does not work #include <iostream> #include <fstream> #include <map> #include <vector> enum val_list {Foo, Bar}; int main() { std::map<int, val_list> val_map; std::vector<std::string> dummy_data = {"0","1","3"}; val_map.insert(0,static_cast<val_list>(std::stoi(dummy_data[0]))); } I get the following compiler error test.cc:17:66: error: no matching function for call to ‘std::map<int, val_list>::insert(int, val_list)’ 17 | val_map.insert(0,static_cast<val_list>(std::stoi(dummy_data[0]))); This toy example is similar to my actual program, which gives me a slightly different error with the same structure enum PhysicalNames {unassigned,top_points, side_points, bottom_points, top_lines, side_lines, bottom_lines, symetry_line, top_surface,side_surface,bottom_surface}; std::vector<std::string> entity_data; std::map<int, PhysicalNames> node_map; node_map.insert(std::stoi(entity_data[0]),group); This gives me the same error but with a reference variable which is weird error: no matching function for call to ‘std::map<int, PhysicalNames>::insert(int, PhysicalNames&)’ 284 | node_map.insert(std::stoi(entity_data[0]),group); What am I doing wrong, exactly?
You are using the std::map::insert wrong! The std::map::insert expect a std::map::value_type (i.e std::pair<const Key, T>) as argument there, not the key and value. In your first example, this is std::pair<const int, val_list>. From cppreference.com overloads (1) and (3): std::pair<iterator, bool> insert( const value_type& value ); (1) // ^^^^^^^^^^^^^^^^^^^^^^^^ std::pair<iterator, bool> insert( value_type&& value ); (3) (since C++17) // ^^^^^^^^^^^^^^^^^^ That means you need extra {} there, so that value_type be constructed on the go: val_map.insert({ 0, static_cast<val_list>(std::stoi(dummy_data[0])) }); // ^^^ ^^^ Alternatively, mention the value_type while passing val_map.insert(std::pair<const int, val_list>{ 0, static_cast<val_list>(std::stoi(dummy_data[0])) }); or std::make_pair while passing val_map.insert(std::make_pair( 0, static_cast<val_list>(std::stoi(dummy_data[0])) )); This could have been avoided if you have used std::map::emplace. As a plus, the map entry will be constructed in place in the map. val_map.emplace(0, static_cast<val_list>(std::stoi(dummy_data[0])) ); As a side note, use enum struct or enum class, which provids type safety over the plane enums. Read more: Why is enum class preferred over plain enum?
74,114,559
74,114,642
Compiler optimizations on map/set in c++
Does compiler make optimzation on data structures when input size is small ? unordered_set<int>TmpSet; TmpSet.insert(1); TmpSet.insert(2); TmpSet.insert(3); ... ... Since since is small using hashing would be not required we can simply store this in 3variables. Do optimization like this happen ? If yes who is responsible for them ? edit: Replaced set with unordered_set as former doesn't do hasing.
Possible in theory to totally replace whole data structures with a different implementation. (As long as escape analysis can show that a reference to it couldn't be passed to separately-compiled code). But in practice what you've written is a call to a constructor, and then three calls to template functions which aren't simple. That's all the compiler sees, not the high-level semantics of a set. Unless it's going to optimize stuff away, real compilers aren't going to use a different implementation which would have different object representations. If you want to micro-optimize like this, in C++ you should do it yourself, e.g. with a std::bitset<32> and set bits to indicate set membership. It's far too complex a problem for a compiler to reliably do a good job. And besides, there could be serious quality-of-implementation issues if the compiler starts inventing different data-structures that have different speed/space tradeoffs, and it guesses wrong and uses one that doesn't suit the use-case well. Programmers have a reasonable expectation that their compiled code will work somewhat like what they wrote, at least on a large scale. Including calling those standard header template functions with their implementation of the functions. Maybe there's some scope for a C++ implementation adapting to the use-case, but I that would need much debate and probably a special mechanism to allow it in practice. Perhaps name-recognition of std:: names could be enough, making those into builtins instead of header implementations, but currently the implementation strategy is to write those functions in C++ in .h headers. e.g. in libstdc++ or libc++.
74,114,617
74,114,801
invalid conversion from 'int' to 'unsigned char*'
Obviously, I'm doing something stupid here, can someone help? The following code: void Encode::getHighNibble(unsigned char* highNibble) { highNibble = (this->word & 0xe0) >> 1; //highNibble |= (this->word & 0x10) >> 2;} unsigned char word; // it declared as uint8 Gives me the following compilation error: invalid conversion from 'int' to 'unsigned char*'
In this line: highNibble = (this->word & 0xe0) >> 1; highNibble is a pointer (to unsigned char). It can only be assigned to some address containing an unsigned char, and (this->word & 0xe0) >> 1 doesn't look like one. In case you actually wanted to assign the value to the memory where highNibble is pointing to, you should use *highNibble (i.e. dereference the pointer). Also the type of the expression (this->word & 0xe0) >> 1 is int (as your compiler told you). So you should cast it to unsigned char. Fixed version: *highNibble = static_cast<unsigned char>((this->word & 0xe0) >> 1); Edit: As @Persixty suggested in the comment below, if you want to extract the high nibble of a byte, you should actually use the expression: ((this->word) >> 4) (or (((this->word) >> 4) & 0x0F) if word was not 8 bit).
74,115,427
74,115,830
How to get the maximum value of an Eigen tensor?
I am trying to find the maximum value of an Eigen tensor. I know how to do this using Eigen matrices but obviously this is not working for a tensor: Example static const int nx = 4; static const int ny = 4; static const int nz = 4; Eigen::Tensor<double, 3> Test(nx,ny,nz); Test.setZero(); Eigen::Tensor<double, 3> MaxTest(nx,ny,nz); MaxTest.setZero(); MaxTest = Test.maxCoeff(); Usually for an Eigen matrix I would do the following: MaxTest = Test.array().maxCoeff(); But this is not working, instead I get the error: class "Eigen::Tensor<std::complex<double>, 3, 0, Eigen::DenseIndex>" has no member "maxCoeff" Is there another way to get the maximum value of this tensor? Something equivalent to max(max(max(tensor))) in MATLAB.
You can use maximum(), see the documentation: static const int nx = 4; static const int ny = 4; static const int nz = 4; Eigen::Tensor<double, 3> MaxTest(nx,ny,nz); MaxTest.setZero(); Eigen::Tensor<double, 0> MaxAsTensor = MaxTest.maximum(); double Max = MaxAsTensor(0); std::cout << "Maximum = " << max_dbl << std::endl;
74,115,613
74,115,714
Partial specialization of non-type parameter
I understand how specialization works for type/pointer to type: template <typename T> class TestClass { public: TestClass() { std::cout << "TestClass: general" << std::endl; } }; template <typename T> class TestClass<T*> { public: TestClass() { std::cout << "TestClass: pointer" << std::endl; } }; TestClass<int> tc1; //TestClass: general TestClass<int*> tc2; // TestClass: pointer but if we have template<auto N> class S { public: S() { std::cout << "auto template" << std::endl; } }; template<char N> class S<N> { public: S() { std::cout << "char template" << std::endl; } }; If I use it like: S<20U> s1; //char template S<'c'> s2; //char template in both case I get char template; What is the meaning of writing template<char N> class S<N> and when the 'auto' template will be called then?
when the 'auto' template will be called then? The primary template template<auto N> class S will be used whenever the non-type parameter N is of type other than char. This means that it will be used for S<20U> s1; //auto template GCC Demo Output: auto template char template Here is the clang bug: Clang chooses specialization over primary template for non-type template parameter Here is the msvc bug: MSVC chooses specialization over primary template for non-type template parameter
74,115,861
74,117,309
Incomplete type error when trying to create a BluetoothLEAdvertisementPublisher?
I have problem with Windows SDK. There are .h header files. Classes declared in this files look like this: namespace ABI { namespace Windows { namespace Devices { namespace Bluetooth { namespace Advertisement { class BluetoothLEAdvertisementPublisher; } /*Advertisement*/ } /*Bluetooth*/ } /*Devices*/ } /*Windows*/ } When i want to create class, compiler raises me error 'allocation of incomplete type'. BluetoothLEAdvertisementPublisher* x = new BluetoothLEAdvertisementPublisher(); What is going on. How should i use this? I have windows 10, C++ 11 and mingw compiler.
BluetoothLEAdvertisementPublisher comes with WinRT, not the Win32 API that MinGW provides. So there is no way you will be able to compile that with MinGW/MinGW-w64 and you should try it with MSVC instead.
74,116,507
74,116,550
How can I call a method of an object in a list iterator in C++?
I have a list of Point objects in C++11 and I want to combine each point's string value into a longer string. I have a method to get the point as a string in a certain format, but I can't figure out how to call that method while iterating through the list. This is my code: list<Point> points; string results = ""; for (int i = 0; i < num_points; i++) { Point ptemp = Point(random01(), random01()); points.push_back(ptemp); results += ptemp.getStr(); } string log_output = ""; string sep = ","; list<Point>::iterator iter; for (iter = points.begin(); iter != points.end(); ++iter) { // get the first three points in the log.txt format log_output += *iter.getRawStr(",") + " , "; } I'm getting this error: error: ‘std::__cxx11::list<Point>::iterator’ {aka ‘struct std::_List_iterator<Point>’} has no member named ‘getRawStr’ 177 | log_output += *iter.getRawStr(",") + " , "; I've tried taking away the asterisk, using to_string() instead, and reformatting the loop to use an increasing integer i with the iterator methods called separately inside the loop, but it still doesn't work. I've also tried researching it, but I've only seen cout << *iter, not how to specifically call methods from the iterator. What should I do?
It's a case of operator precedence. The . binds more tightly than *, so this *iter.getRawStr(",") is actually this *(iter.getRawStr(",")) That is, it tries to call getRawStr on the iterator (not the thing it's pointing to), and then dereference the result. You want (*iter).getRawStr(",") which is equivalent[1] to iter->getRawStr(",") [1] Technically, operator -> can be overridden, so a pathological class might define it to do something different than unary *, but no normal, sane C++ class should do this.
74,116,686
74,117,977
How do you get the network interface index for the loopback interface?
I'm writing an app that needs to bind to the loopback interface by interface index. The lazy way to do this would just be to use interface index 1, or even use if_nametoindex("lo0"). However, is that technically correct? Is lo0 guaranteed to exist, and be the network interface with index 1? If so, that answers my question, but if not, what's the correct way to get the loopback interface's index? (Note: This is in regards to Unix-like environments like macOS or Linux, not Windows.)
Given that loopback interfaces can be added and removed, I wrote a function to find the first one and return its index. It returns 0 if there are no loopback interfaces (or it fails to get information about the available interfaces). #include <ifaddrs.h> #include <net/if.h> #include <net/if_dl.h> #include <net/if_types.h> uint32_t loopbackInterfaceIndex() { uint32_t result = 0; ifaddrs *interfaces; if (getifaddrs(&interfaces) == -1) { return 0; } for(ifaddrs *interface = interfaces; interface; interface = interface->ifa_next) { if (interface->ifa_addr && interface->ifa_addr->sa_family == AF_LINK) { sockaddr_dl *addr = (sockaddr_dl *)interface->ifa_addr; if (addr->sdl_type == IFT_LOOP) { result = if_nametoindex(interface->ifa_name); break; } } } freeifaddrs(interfaces); return result; }
74,116,771
74,117,709
How can i properly use the .find() function from set in C++?
Here is the struct for 'point' struct point { double x; double y; }; and here is the function that produces an error, there is an issue with my use of .find() as show in the pic below. When I hover over the error it says "In template: invalid operands to binary expression ('const point' and 'const point')" bool isChecked(point left, point right, set<vector<point>>const& inSet) { // Check both possible arrangements of points vector<point> tmp1 = {left, right}; vector<point> tmp2 = {right, left}; // .find() returns an iterator up to the element found // If not found, return element after last, .end() auto first = inSet.find(tmp1); auto second = inSet.find(tmp2); // Check if elements were checked already if (first != inSet.end() || second != inSet.end()) return true; return false; } Here is the error provided by compiler: C:/msys64/mingw64/include/c++/12.2.0/bits/predefined_ops.h:45:23: error: no match for 'operator<' (operand types are 'const point' and 'const point') 45 | { return *__it1 < *__it2; } | ~~~~~~~^~~~~~~~ In file included from C:/msys64/mingw64/include/c++/12.2.0/string:47: C:/msys64/mingw64/include/c++/12.2.0/bits/stl_iterator.h:1246:5: note: candidate: 'template<class _IteratorL, class _IteratorR, class _Container> bool __gnu_cxx::operator<(const __normal_iterator<_IteratorL, _Container>&, const __normal_iterator<_IteratorR, _Container>&)' 1246 | operator<(const __normal_iterator<_IteratorL, _Container>& __lhs, | ^~~~~~~~ C:/msys64/mingw64/include/c++/12.2.0/bits/stl_iterator.h:1246:5: note: template argument deduction/substitution failed: C:/msys64/mingw64/include/c++/12.2.0/bits/predefined_ops.h:45:23: note: 'const point' is not derived from 'const __gnu_cxx::__normal_iterator<_IteratorL, _Container>' 45 | { return *__it1 < *__it2; } | ~~~~~~~^~~~~~~~ C:/msys64/mingw64/include/c++/12.2.0/bits/stl_iterator.h:1254:5: note: candidate: 'template<class _Iterator, class _Container> bool __gnu_cxx::operator<(const __normal_iterator<_Iterator, _Container>&, const __normal_iterator<_Iterator, _Container>&)' 1254 | operator<(const __normal_iterator<_Iterator, _Container>& __lhs, | ^~~~~~~~ C:/msys64/mingw64/include/c++/12.2.0/bits/stl_iterator.h:1254:5: note: template argument deduction/substitution failed: C:/msys64/mingw64/include/c++/12.2.0/bits/predefined_ops.h:45:23: note: 'const point' is not derived from 'const __gnu_cxx::__normal_iterator<_Iterator, _Container>' 45 | { return *__it1 < *__it2; } | ~~~~~~~^~~~~~~~ ninja: build stopped: subcommand failed.
you need to add this to your code: bool operator<(const point& lhs, const point& rhs) { return lhs.x < rhs.x; } to overload the < operator. and then you write your function and you can write it like this: bool isChecked(point left, point right, set<vector<point>> inSet) { // Check both possible arrangements of points vector<point> tmp1 = {left, right}; vector<point> tmp2 = {right, left}; if (inSet.find(tmp1) != inSet.end() || inSet.find(tmp2) != inSet.end()) { return true; } else { return false; } }
74,117,125
74,117,337
Why does strcpy() force this for()-loop to iterate once more than without strcpy() and cause a segmentation fault?
I'm trying to implement my own Linux shell using C++. The following code is working fine: #include <string.h> #include <sstream> #include <iostream> #include <vector> #include <unistd.h> #include <wait.h> #include <stdio.h> using namespace std; int main() { // read the input command/arguments cout << "myshell >> "; string input; getline(cin, input); // if command is 'exit', exit myshell if (input == "exit") { cout << exit; exit(0); } // init stringstream stringstream in_stream(input); // create vector to store the parts of the command vector<string> parts; // string to store the parts during one iteration string part; // read all parts of the stringstream, separated by ' ' (space) while (getline(in_stream, part, ' ')) { parts.push_back(part); } // create c-like array for passing it to the execvp() system call // execvp() needs nullptr as last element, thus: size() + 1 const char* parts_arr[parts.size()+1]; // store all elements of the parts vector in parts_arr as c-like strings for (int i = 0; i < parts.size(); i++) { parts_arr[i] = parts[i].c_str(); } // last element must be nullptr parts_arr[parts.size()] = nullptr; // init some variables int pid; int status; // fork and check the returned pid switch (pid = fork()) { case -1: cerr << "fork() encountered an error." << endl; return 1; case 0: // child process if (execvp(parts_arr[0], const_cast<char *const *>(parts_arr)) == -1) { cerr << "Child: execvp() encountered an error." << endl; return 1; } default: // parent process if (waitpid(pid, &status,0) != pid) { cerr << "Parent: wait() encountered an error." << endl; return 1; } cerr << "Parent: child " << pid << " ended with status " << WEXITSTATUS(status) << endl; // least significant bits transport additional information return 0; } } Output: $ ./myshell myshell >> ls -l total 92 -rwxrwxr-x 1 ubuntu ubuntu 41576 Oct 17 13:24 a.out -rwxrwxr-x 1 ubuntu ubuntu 41824 Oct 18 22:19 myshell -rw-rw-r-- 1 ubuntu ubuntu 2140 Oct 18 22:19 myshell.cpp Parent: child 10538 ended with status 0 As one might think (me included): the const_cast in the execvp()-call just does not look right, so I was trying to clean-up and rewrite my code to eliminate the need for this cast. Doing this, I encountered a problem modifying the creation of the c-like string array for the execvp() system call leading to a Segmentation fault (core dumped) error. The following code snippets are the only lines of code I changed: (...) // create c-like array for passing it to the execvp() system call // execvp() needs nullptr as last element, thus: size() + 1 char* parts_arr[parts.size()+1]; // <-- changed // store all elements of the parts vector in parts_arr as c-like strings for (int i = 0; i < parts.size(); i++) { strcpy(parts_arr[i], parts[i].c_str()); // <-- changed } (...) case 0: // child process if (execvp(parts_arr[0], parts_arr) == -1) // <-- changed { cerr << "Child: execvp() encountered an error." << endl; return 1; } (...) Output: $ ./myshell myshell >> ls -l Segmentation fault (core dumped) While debugging, I found that with the original code the for-loop iterates correctly, but using the new code it keeps iterating and causes the segmentation fault due to the faulty indexing. Why does this happen? From my understanding, the for-loop should work equally for both codes, as the changes do not affect anything related to the iteration of the loop. Also, I am open for any suggestion on how to improve the whole command/argument parsing, maybe completely eliminating the need for the conversion from the string-vector to the c-like string array.
char* parts_arr[parts.size()+1]; // <-- changed The size of an array variable must be compile time constant. parts.size()+1 is not compile time constant. The program is ill-formed. That issue was already in the original version. However, let's assume that you use non-standard language extensions that allow this. The array contains pointers. You've default initialised the array, and thus the pointers have indeterminate values. strcpy(parts_arr[i], parts[i].c_str()); strcpy requires that the fist argument is a valid pointer to sufficiently large amount of memory to fit the entire string. The pointers that you pass into strcpy are not valid pointers to sufficiently large amount of memory to fit the entire string. Not only does that violate the pre-conditions of the function, but also reading any indeterminate value of pointer type is never allowed. The behaviour of the program is undefined. I was trying to clean-up and rewrite my code to eliminate the need for this cast. Introducing strcpy is counter productive for "clean-up". It's a relic from C that you should avoid using it in C++. There's a much easier way to avoid the cast. Changing the type of the array element to char* is a good start for minimal change. Only other change you need is to use std::string::data instead of std::string::c_str: parts_arr[i] = parts[i].data();
74,117,858
74,117,874
sizeof behavior, fit a class within a memory space?
I am trying to verify that an instance of a class will fit in a queue (defined by a C library), and noticed that sizeof() didn't do what I thought it did. #include <iostream> using namespace std; class A { int x, y, z; public: A() {} void PrintSize() { cout << sizeof(this) << endl; } }; class B : public A { int a, b, c; public: B() {} void PrintSize() { cout << sizeof(this) << endl; } }; int main() { A a; B b; a.PrintSize(); // is 8 b.PrintSize(); // is 8 cout << sizeof(a) << endl; cout << sizeof(b) << endl; } returns: 8 8 12 24 I did not expect the "8" values - why is it different when taken within the class? How can verify that the class that I define fits within a memory space, especially at compile time?
This expression sizeof(this) gives the size of the pointer this. It seems you mean the size of the corresponding class sizeof( *this )
74,118,999
74,119,544
(C++) How can I inherit a template class in its specilization class?
If I have a class like: Vector<T> (a template class), and now I want to specialize it: Vector<int>. How can I inherit from Vector<T>? My code is: template<typename T> class Vector&<int>:public Vector <T> But it gives error: template parameters not deducible in partial specialization. How should I deal with it? I don't actually mean I want to use in Vector. But I want to understand what's wrong in langugae aspect? Is that means specilization class can't inherit from other template classes?
It looks like you want the specialised Vector<int> to inherit from the general Vector<int>. This is not possible as is, because there can be only one Vector<int>, but with a little trick you can do it. Just add another template parameter, a boolean non-type with a default value. Now for each T, there are two different Vector<T, b>, one for each possible b. template <class T, bool = true> class Vector { void whatever(); }; Regular users just use Vector<float> or Vector<int> without explicitly passing the second argument. But specialisations can pass false if they need to. template<> class Vector<int, true> : public Vector<int, false> { int additional_member; };
74,119,421
74,119,673
std::filesystem::copy() only copies files in folder
I am trying to copy a folder to another folder using std::filesystem::copy(), so far it only copies the files and folders within the folder I'm trying to move over, instead of the folder itself. Any ideas why? I know this could be done manually by creating a new directory using std::filesystem::create_directory(), but it won't carry over the security info and permissions from the original folder. EDIT: path = C:\Users\Test\Folder nPath = C:\Users\Test\Movehere boolean CopyToPath(std::string path, std::string nPath) { if (fs::exists(path) && fs::exists(nPath)) { try { //path = Folder To Copy, nPath = Destination fs::copy(path, nPath, fs::copy_options::overwrite_existing | fs::copy_options::recursive); return true; } catch (fs::filesystem_error e) { std::cout << e.what() << "\n"; return false; } } else return false; }
This is expected behavior, as documented at https://en.cppreference.com/w/cpp/filesystem/copy: Otherwise, if from is a directory and either options has copy_options::recursive or is copy_options::none, If to does not exist, first executes create_directory(to, from) (creates the new directory with a copy of the old directory's attributes) Then, whether to already existed or was just created, iterates over the files contained in from as if by for (const std::filesystem::directory_entry& x : std::filesystem::directory_iterator(from)) and for each directory entry, recursively calls copy(x.path(), to/x.path().filename(), options | in-recursive-copy), where in-recursive-copy is a special bit that has no other effect when set in options. (The sole purpose of setting this bit is to prevent recursive copying subdirectories if options is copy_options::none.) In other words, copy() does not copy the source directory itself, only the contents of the directory. If your goal is to make a copy of Folder itself inside of Movehere, ie C:\Users\Test\Movehere\Folder, then you will have to extract Folder from the source directory and append it to the target path, eg: fs::path src = "C:\\Users\\Test\\Folder"; fs::path dest = "C:\\Users\\Test\\Movehere"; dest /= src.filename(); fs::create_directory(dest, src); // only because CopyToPath() requires this due // to its use of fs::exists(), instead of letting // fs::copy() create it... CopyToPath(src, dest);
74,119,498
74,119,617
How to send a class (not object) in a parameter in C++?
I want to send a class (not an object) as a parameter. In Delphi, I can use this: TDemo = class of baseclass; In C++, how can I write this?
C++ has no equivalent to Delphi metaclass types, so what you are asking for is simply not possible.
74,119,510
74,119,643
Can we declare C++ function always as inline?
I saw a piece of information about behavior of C++ compilers with inline function as below, which says: https://cplusplus.com/doc/tutorial/functions/ When function is declared with inline, most compilers already optimize code to generate inline functions when they see an opportunity to improve efficiency; Even if not explicitly marked with the inline specifier. Therefore, this specifier merely indicates the compiler that inline is preferred for this function, although the compiler is free to not inline it, and optimize otherwise. In C++, optimization is a task delegated to the compiler, which is free to generate any code for as long as the resulting behavior is the one specified by the code. If its delegated to compiler, which functions has to inline and which not, as per optimization, can we always declare a function as inline ? After all, it would be done by compiler if its optimum.
As general rules: You should mark a function inline if you intent to define it in a header file (included by multiple translation units, aka .cpp files). It is not allowed to define a function which is not inline in multiple translation units. So this is necessary. If the function is also static (at namespace scope), constexpr, is a function template or is defined inside a class definition, then inline is redundant and can/should be left out. If the function is defined in a .cpp file and only used in this one translation unit it may be declared inline, but any performance implications of that are at best going to be minimal. A compiler will make its own decision on inlining anyway. inline is either completely ignored or a minor hint in the decision making process at best. If the function is defined in a .cpp file and a declaration of it is included in multiple translation units via a header file, then it must not be declared inline. The inline specifier implies that you guarantee that a definition of the function will be available in any translation unit using it (and that all definitions will be identical). The thing that is really performance-relevant here is not the inline specifier as such, but making the decision of whether you want to include the function definition in all translation units (meaning a header file) or only in one translation unit (meaning a .cpp file). Including in all translation units means that the compiler has it easier to perform inlining, not due to the inline keyword, but the fact that the definition is visible during the compilation process for the unit. However, nowadays we also have link time optimization which applies optimizations across all translation units when enabled and for which even that visibility of the definition doesn't really matter anymore.
74,119,960
74,120,155
Why an unordered_map can be passed to a queue with pair parameter?
class Solution { public: class mycomparison { public: bool operator()(const pair<int, int>& lhs, const pair<int, int>& rhs) { return lhs.second > rhs.second; }// the paremeter is pair<int,int> ** }; vector<int> topKFrequent(vector<int>& nums, int k) { unordered_map<int, int> map; for (int i = 0; i < nums.size(); i++) { map[nums[i]]++; } priority_queue<pair<int, int>, vector<pair<int, int>>, mycomparison> pri_que;// the priority_queue's paremeter is also pair<int,int> for (unordered_map<int, int>::iterator it = map.begin(); it != map.end(); it++) { pri_que.push(*it);// but unordered_map is passed as parameter of pri_que not pair<int,int> if (pri_que.size() > k) { pri_que.pop(); } } vector<int> result(k); for (int i = k - 1; i >= 0; i--) { result[i] = pri_que.top().first; pri_que.pop(); } return result; } }; Why is the parameter different? My notes describe it: the parameter of the priority_queue should be a pair but an unordered_map is passed. When I run it, it is correct. Why?
You are confusing the STL container (in your case, a std::unordered_map) with the object(s) referred to by that container's iterator. STL containers are collections of a given type of object and each has associated iterators, which refer to particular objects within the collection. So, for example, a std:vector<int> will be a collection of int types but its iterators will provide references to the contained objects, which will be of type int. Iterators are, in many ways, like pointers, but not quite; see: Is an iterator in C++ a pointer? For the STL "map" containers (including the unordered_map class that you are using), each object in the container is a pair, comprising a (constant) "key" and a corresponding "value". In your case, you have defined both the key and the value to be of type int – so each object in the map will be of pair<const int, int> type. The it iterator in your first for loop will run through the map, referring ('pointing') to each of its elements in turn. When you dereference that iterator (using the * in *it) you will get the referred-to object, in each iteration of the loop. That object will, in each case, be a pair<const int, int>, so it is a valid argument for your call to pri_que.push.
74,120,075
74,120,110
String concatenation c++ giving unexpected answer
I was solving a problem on leetcode: Count and say, and wrote the following program: #include <bits/stdc++.h> using namespace std; class Solution { public: string countAndSay(int n) { string ans = ""; if (n == 1) { return "1"; } string say = countAndSay(n - 1); int j = 0, i = 0; while (i < say.size()) { while (say[j] == say[i] && j < say.size()) { j++; } int diff = j - i; ans += to_string(diff); ans += to_string(say[i]); i = j; } return ans; } }; int main() { Solution sol; cout << sol.countAndSay(4) << "\n"; return 0; } while i was expecting "1211", it was giving "149152157149153150149153155" as an answer. I tried to debug this and found that ans += to_string(say[i]); this was concatenating unexpected value. eg:- say="1", i=0, j=1, diff = 1 and ans="" after ans += to_string(diff); has already concatenated "1", instead of concatenating "1" to_string(say[i]); is concatenating "49". Can anyone please explain what is happening?
ans += to_string(say[i]); That line ends up converting say[i] as an integer (because char is an integer type!). Solution, add it as a character: ans += say[i]; For your convenience: https://en.cppreference.com/w/cpp/string/basic_string/to_string And the lesson here is: if a line with a library function call does funny thing things, read the docs of the function.
74,120,078
74,122,293
How to pass an Eigen tensor to a function correctly?
I am having some trouble passing a function inside another function with Eigen tensor. For example, calling the Function1 in the main.cpp code and it works fine, but calling inside of Function2 is causing an error. void Function1(Eigen::Tensor<std::complex<double>, 3>& vark, Eigen::Tensor<double, 3> Kin, Eigen::Tensor<std::complex<double>, 3>& Out){ Out = vark * Kin * 1i; } void Function2(Eigen::Tensor<std::complex<double>, 3>& In, Eigen::Tensor<std::complex<double>, 3>& kin){ Eigen::Tensor<std::complex<double>, 3> out(nx,ny,nz); out.setZero(); Function1(In, kin, Out); //error in Kin as it's passed from the function } The error I get: error: cannot convert ‘Eigen::TensorEvaluator<Eigen::Tensor<double, 3>, Eigen::DefaultDevice>::EvaluatorPointerType’ {aka ‘double*’} to ‘Eigen::TensorEvaluator<const Eigen::Tensor<std::complex<double>, 3>, Eigen::DefaultDevice>::EvaluatorPointerType’ {aka ‘const std::complex<double>*’} 152 | return m_rightImpl.evalSubExprsIfNeeded(m_leftImpl.data()); | ^ | | | Eigen::TensorEvaluator<Eigen::Tensor<double, 3>, Eigen::DefaultDevice>::EvaluatorPointerType {aka double*} I am confused why is this happening. EDIT: I added the header file for the two functions: void Function1(Eigen::Tensor<std::complex<double>, 3>& vark, Eigen::Tensor<double, 3> Kin, Eigen::Tensor<std::complex<double>, 3>& Out); void Function2(Eigen::Tensor<std::complex<double>, 3>& In, Eigen::Tensor<std::complex<double>, 3>& kin);
The Kin argument of Function1() is a tensor of double, not of complex<double>. Yet, in Function2() you pass in a complex<double>. So the compiler complains that it cannot convert a tensor of complex<double> to one of double. Fix: Change the Kin argument to Eigen::Tensor<std::complex<double>, 3>, and also add const& for performance reasons: void Function1( Eigen::Tensor<std::complex<double>, 3> const & vark, Eigen::Tensor<std::complex<double>, 3> const & Kin, Eigen::Tensor<std::complex<double>, 3> & Out) { Out = vark * Kin * 1i; } Note: You might also find the documentation about passing Eigen types to functions interesting.
74,120,204
74,151,148
Create a graph if nodes are not continuous c++
Consider this situation: (undirected graph) we dont have number of nodes but have the edges like 1<->3 , 6<->7, 3<->7. So how do we declare a graph using this? Generally we have n that is no. of node and e edges but in this case we only have e edges and that too not continuous i.e. instead of 1,2,3,4(or zero indexed) we have 1,3,6,7. I know we should use a map to convert these 1,3,6,7 values to 1,2,3,4 but how? how we generally declare a graph vector<int> adj[100000]; for(int i=0;i<e;i++) { int u,v; cin>>u>>v; //need some mapping technique here to make this continuous adj[u].push_back(v); adj[v].push_back(u); } //iterate according to situation
I tried few combinations and this approach works well e-> no. of edges this approach maps the input vertices to respective values in map from 0 based index. Helpful to apply various algorithms directly without worrying about the input as much. int i=0; while(e>=0) { e--; int a1,a2; cin>>a1>>a2; //a1 if(mp.find(a1)!=mp.end()) a1 = mp[a1]; else { mp[a1] = i; a1 = i; i++; } //a2 if(mp.find(a2)!=mp.end()) a2 = mp[a2]; else { mp[a2] = i; a2 = i; i++; } adj[a1].push_back(a2); adj[a2].push_back(a1); }
74,120,209
74,120,874
How to delete an array that is in a struct inside a struct c++
This is for an assignment for one of my classes and I am stuck, I have to use these required structs, those being: struct Pokemon { int dex_num; string name; string type; int num_moves; string* moves; }; struct Pokedex { string trainer; int num_pokemon; Pokemon* dex; }; I was tasked to create an array of pokemon with the available information from a .txt file. I name the Pokedex struct "Pokedex data;" what I am stuck on is the erasing of said array void delete_info(Pokedex &); The function above this text is how I have to delete it, and I am confused I have tried delete []data.dex; data.dex = NULL; I have tried to dereference it and I have tried delete []dex; delete []data; etc. Every single one has led me into a seg fault, or just general bugs and declaration issues. edit this is how I was supposed to allocate the memory Pokemon * dex = create_pokemons(7); this is what I called for in my main Pokemon* create_pokemons(int y) { Pokemon* dex = new Pokemon[y]; return dex; } i'm not quite sure what went wrong. edit I am not allowed to use vectors #include <iostream> #include <string> #include <fstream> using namespace std; struct Pokemon { int dex_num; string name; string type; int num_moves; string* moves; }; struct Pokedex { string trainer; int num_pokemon; Pokemon* dex; }; string getName(string&); Pokemon* create_pokemons(int); void populate_pokedex_data(Pokedex & , ifstream &); string* create_moves(int); void populate_pokemon(Pokemon &, ifstream &); void delete_info(Pokedex &); int main () { Pokedex data; int y; ifstream myFile; Pokemon * dex = create_pokemons(6); populate_pokedex_data(data , myFile); delete_info(data); if(myFile.is_open()) { myFile.close(); } } Pokemon* create_pokemons(int y) { Pokemon* dex = new Pokemon[y]; return dex; } string getName(string &str) { cout << "What is your name trainer" << endl; cin >> str; cout << str << " is your name, thats pretty cringe" << endl; return str; } void populate_pokedex_data(Pokedex &data, ifstream &myFile) { string str; myFile.open("pokedex.txt",ios::in); myFile >> data.num_pokemon; data.trainer = str; for (int i =0; i < data.num_pokemon; i++) { populate_pokemon(data.dex[i], myFile); } } void populate_pokemon(Pokemon &dex, ifstream &myFile) { string str; myFile >> dex.dex_num; myFile >> dex.name; myFile >> dex.type; myFile >> dex.num_moves; getline(myFile, str); cout << dex.dex_num <<" "; cout << dex.name << " "; cout << dex.type << " "; cout << dex.num_moves << endl; } void delete_info(Pokedex &data) { delete [] data.dex; data.dex = NULL; }
Your implementation of delete_info() is correct. The real problem is that your main() is creating an array of Pokemon objects but never assigning that array pointer to the Pokedex::dex field, or even initializing the Pokedex::dex field at all. So, your code has undefined behavior when it tries to access the content of that array, or free the array, using the Pokedex::dex field. In main(), you need to change this: Pokemon * dex = create_pokemons(6); To this instead: data.dex = create_pokemons(6); And then, that statement should actually be moved inside of populate_pokedex_data() instead, after the value of data.num_pokemon is determined, eg: void populate_pokedex_data(Pokedex &data, ifstream &myFile) { string str; myFile.open("pokedex.txt",ios::in); myFile >> data.num_pokemon; data.trainer = str; // <-- you didn't read a value into str first! data.dex = create_pokemons(data.num_pokemon); // <-- moved here! for (int i =0; i < data.num_pokemon; i++) { populate_pokemon(data.dex[i], myFile); } }
74,120,558
74,128,609
Any optimization about random access array modification?
Given an array A of size 105. Then given m (m is very large, m>> the size of A) operations, each operation is for position p, increasing t. A[p]+=t Finally, I output the value of each position of the whole array. Is there any constant optimization to speed up the intermediate modification operations? For example, if I sort the positions, I can modify them sequentially to avoid random access. However, this operation will incur an additional sorting cost. Is there any other way to speed it up? Trying to re-execute all operations after sorting can be an order of magnitude faster than executing them directly. But the cost of sorting is too high.
On architectures with many cores, the best solution is certainly to perform atomic accesses of A[p] in parallel. This assume the number of cores is sufficiently big for the parallelism to not only mitigate the overhead of the atomic operations but also be faster than the serial implementation. This can be pretty easily done with OpenMP or with native C++ thread/atomics. The number of core need not to be too huge, otherwise, the number of conflict may be significantly bigger causing contention and so decreasing performance. This should be fine since the number of item is pretty big. This solution also assume the accesses are quite uniformly random. If they are not (eg. normal distribution), then the contention can be too big for the method to be efficient. An alternative solution is to split the accesses between N threads spacially. The array range can be statically split in N (relatively equal) parts. All the threads read the inputs but only the thread owning the target range of the output array write into it. The array parts can then be combined after that. This method works well with few threads and if the data distribution is uniform. When the distribution is not uniform at all (eg. normal distribution), then a pre-computing step may be needed so to adjust the array range owned by threads. For example, one can compute the median, or event the quartiles so to better balance the work between threads. Computing quartiles can be done using a partitioning algorithm like Floyd Rivest (std::partition should not be too bad despite I expect it to use a kind of IntroSelect algorithm that is often a bit slower). The pre-computation may be expensive but this should be significantly faster than doing a sort. Using OpenMP is certainly a good idea to implement this. Another alternative implementation is simply to perform the reduction separately in each thread and then sum up the final array of each thread in a global array. This solution works well in your case (since "m >> the size of A") assuming the number of core is not too big. If so, on need to mix this method with the first one. This last method is probably the simplest efficient method.
74,120,876
74,120,936
Can't std::move packed field in GCC, but can in CLang
Following code doesn't compile in GCC, but compiles in CLang: See on GodBolt #include <utility> struct __attribute__((__packed__)) S { int a = 0; }; int main() { S s; auto x = std::move(s.a); // error here } GCC error: <source>:9:26: error: cannot bind packed field 's.S::a' to 'int&'. How can I fix this? Is it possible somehow to replace auto x with some packed type like int __attribute__((__packed__)) x to resolve this? If I remove std::move then auto x = s.a; compiles in both GCC & CLang. Note. This is only a toy minimal reproducible example. I move int in it only as example, but my real class is templated with any type T, not only int.
This appears to work: auto x = std::move(*&s.a); Though this also emits <source>:9:26: warning: taking address of packed member 'a' of class or structure 'S' may result in an unaligned pointer value [-Waddress-of-packed-member] on both GCC and Clang.
74,120,975
74,121,015
Create an instance given pointer type in template
Is there a way to call the constructor of a class, given the pointer-type of that class type as the template parameter? MyClass<AnotherClass*> => how to call the default constructor of AnotherClass in MyClass? This one does obviously not work (doesnt compile), because in GetNew the new T and the return type T don't fit together. What would be needed is some kind of "type dereferencing" to come to the class type, given the pointer type. class AnotherClass {}; template <class T> class MyClass { public: // this does obviously not compile virtual T GetNew() { return new T; // how let T be AnotherClass* and to create an AnotherClass instance here? } }; int main() { // this does not compile: MyClass<AnotherClass*> tmp; // here, AnotherClass is **pointer** type AnotherClass* a = tmp.GetNew(); } A workaround would be to use the class type as the template parameter and use poiter types as return types. But this changes the interface, so I would still like a solution to pointer template type. class AnotherClass {}; template <class T> class MyClass2 { public: virtual T* GetNew() { return new T; } }; int main() { // this does work: MyClass2<AnotherClass> tmp2; // here, AnotherClass is **not** pointer type AnotherClass* b = tmp2.GetNew(); } Another workaround could be to use a factory or similar, but I would like to use the default constructor without additional helping structures.
You can use std::remove_pointer to get the type pointed to. Provides the member typedef type which is the type pointed to by T, or, if T is not a pointer, then type is the same as T. E.g. virtual T GetNew() { return new std::remove_pointer_t<T>; }
74,121,612
74,121,826
How to redefine the template class constructor via a macro in C++11?
I want to recorded the line which created the shared_ptr in C++ 11. Here is my way to rewrite shared_ptr as Shared_ptr : template<class T> class Shared_Ptr{ public: Shared_Ptr(T* ptr = nullptr,int line=__LINE__) :_pPtr(ptr) , _pRefCount(new int(1)) , _pMutex(new mutex) { cout<<this<<"is located in "<<line<<endl; } ~Shared_Ptr() { Release(); cout<<this<<endl; } Shared_Ptr(const Shared_Ptr<T>& sp) :_pPtr(sp._pPtr) , _pRefCount(sp._pRefCount) , _pMutex(sp._pMutex) { AddRefCount(); } Shared_Ptr<T>& operator=(const Shared_Ptr<T>& sp) { //if (this != &sp) if (_pPtr != sp._pPtr) { Release(); _pPtr = sp._pPtr; _pRefCount = sp._pRefCount; _pMutex = sp._pMutex; AddRefCount(); } return *this; } T& operator*(){ return *_pPtr; } T* operator->(){ return _pPtr; } int UseCount() { return *_pRefCount; } T* Get() { return _pPtr; } void AddRefCount() { _pMutex->lock(); ++(*_pRefCount); _pMutex->unlock(); } private: void Release() { bool deleteflag = false; _pMutex->lock(); if (--(*_pRefCount) == 0) { delete _pRefCount; delete _pPtr; deleteflag = true; } _pMutex->unlock(); if (deleteflag == true) delete _pMutex; } private: int *_pRefCount; T* _pPtr; mutex* _pMutex; }; class student { int age; public: student(int a):age(a) { } } ; int main() { Shared_ptr<student> Tom(new student(24),__LINE__); } Is there a way to make Shared_ptr<student>Tom(new student(24)) as same as Shared_ptr <student> Tom(new student(24),__ LINE__) in C++11? In other words , invoke class Constructor with the arguments bound to args. I tried to use marco to achieve,but I don't know the correct way how to define the macro of template class constructor. Below is the macro definition I tried to write but wrong template<typename T> #define Shared_ptr<T>::Shared_ptr(T*) Shared_ptr<T>::Shared_ptr(T * ,__LINE__)
Replace int line=__LINE__ in constructor parameters with int line = __builtin_LINE(). It's a non-standard compiler extension, but it works at least in GCC, Clang, and MSVC (i.e. most common compilers). Then Shared_ptr<student> Tom(nullptr); will work. Shared_ptr<student> Tom(42); will not work, because Shared_ptr doesn't have the right constructor, but it has nothing to do with getting the line number.
74,123,491
74,127,927
CMake - Alternate option to FetchContent when the source file already exists locally
I tried building the ORTools github package locally using cmake and it builds without any errors. However the environment which we are planning to ultimately use does not have an outbound network connection. The problem I see is that https://github.com/google/or-tools/blob/v9.4/cmake/dependencies/CMakeLists.txt performs a Git Clone to download the dependencies and add them. Since there is no outbound network access this step fails and I'm unable to build the dependency. To circumvent this we are planning to manually download the dependencies and add them to https://github.com/google/or-tools/blob/v9.4/cmake/dependencies/ folder. I'm pretty new to CMake and I'm not sure what changes have to be made to accommodate this. For example, what would the following snippet need to be changed to if I cloned Zlib v1.2.11 repository and added it to https://github.com/google/or-tools/blob/v9.4/cmake/dependencies/? # ############################################################################## # ZLIB # ############################################################################## if(BUILD_ZLIB) message(CHECK_START "Fetching ZLIB") list(APPEND CMAKE_MESSAGE_INDENT " ") FetchContent_Declare( zlib GIT_REPOSITORY "https://github.com/madler/ZLIB.git" GIT_TAG "v1.2.11" PATCH_COMMAND git apply --ignore-whitespace "${CMAKE_CURRENT_LIST_DIR}/../../patches/ZLIB.patch") FetchContent_MakeAvailable(zlib) list(POP_BACK CMAKE_MESSAGE_INDENT) message(CHECK_PASS "fetched") endif() Can FetchContent_Declare be used to point to a directory that already contains the source files? What's the alternative?
You could specify SOURCE_DIR parameter for FetchContent_Declare and omit download options: FetchContent_Declare( zlib SOURCE_DIR <path/to/existing/directory> PATCH_COMMAND git apply --ignore-whitespace "${CMAKE_CURRENT_LIST_DIR}/../../patches/ZLIB.patch" ) This works in the same way as in ExternalProject_Add command, which options are accepted by FetchContent_Declare.
74,124,172
74,124,529
Add option to CLI based on CMake configuration
I have written a program prg which can be run using bash with some subcommands like so $ prg subcommand1 Output of subcomman1 $ prg subcommand2 Output of subcomman2 The program is written in C++11 and compiled with CMake (3.10+). Now, I'd like to add another optional command, say optional_subcommand. Optional - in a sense that a user can decide whether to compile program with it when configuring Cake. To clarify, when the code is not compiled withoptional_subcommand support, the output should be something along this lines $ prg optional_subcommand Option not supported... The optional_subcommand requires external library to be installed. Hence find_package(SomeLib REQUIRED) must be invoked at some stage by CMake. The code for optional_subcommand requires this library to compile. All I can think of is writing some dummy code for optional_subcommand which is then replaced on request by CMake. I think this can be achieved be asking CMake to overwrite, say optional_subcommand.cpp with either dummy or not. Is proposed solution sensible or perhaps there is a better way to achieve this?
CMake can define a preprocessor symbol and add extra files to your target (below, prg) if needed: if(SomeLib_FOUND) target_compile_definitions(prg PUBLIC HAVE_SOMELIB) target_sources(prg PRIVATE src/optional_subcommand.cpp) endif() You can then wrap the command dispatching code for optional_subcommand with #ifdef HAVE_SOMELIB.
74,124,550
74,126,140
Convert timestamp string into local time
How to convert timestamp string, e.g. "1997-07-16T19:20:30.45+01:00" into UTC time. The result of conversion should be timespec structure as in utimensat input arguments. // sorry, should be get_utc_time timespec get_local_time(const char* ts); P.S. I need solution using either standard Linux/C/C++ facilities (whatever that means) or Boost C++ library.
Assumption: You want the "+01:00" to be subtracted from the "1997-07-16T19:20:30.45" to get a UTC timestamp and then convert that into a timespec. Here is a C++20 solution that will automatically handle the centisecond precision and the [+/-]hh:mm UTC offset for you: #include <chrono> #include <ctime> #include <sstream> std::timespec get_local_time(const char* ts) { using namespace std; using namespace chrono; istringstream in{ts}; in.exceptions(ios::failbit); sys_time<nanoseconds> tp; in >> parse("%FT%T%Ez", tp); auto tps = floor<seconds>(tp); return {.tv_sec = tps.time_since_epoch().count(), .tv_nsec = (tp - tps).count()}; } When used like this: auto r = get_local_time("1997-07-16T19:20:30.45+01:00"); std::cout << '{' << r.tv_sec << ", " << r.tv_nsec << "}\n"; The result is: {869077230, 450000000} std::chrono::parse will subtract the +/-hh:mm UTC offset from the parsed local value to obtain a UTC timestamp (to up to nanosecond precision). If the input has precision seconds, this code will handle it. If the precision is as fine as nanoseconds, this code will handle it. If the input does not conform to this syntax, an exception will be thrown. If this is not desired, remove in.exceptions(ios::failbit);, and then you must check in.fail() to see if the parse failed. This code will also handle dates prior to the UTC epoch of 1970-01-01 by putting a negative value into .tv_sec, and a positive value ([0, 999'999'999]) into .tv_nsec. Note that handling pre-epoch dates is normally outside of the timespec specification, and so most C utilities will not handle such a timespec value. If you can not use C++20, or if your vendor has yet to implement this part of C++20, there exists a header-only library which implements this part of C++20, and works with C++11/14/17. I have not linked to it here as it is not in the set: "standard Linux/C/C++ facilities (whatever that means) or Boost C++ library". I'm happy to add a link if requested.
74,124,586
74,124,876
Recursive Template Instantiation failed with tuples
I have the following code that iterates through the types of a std::tuple and concatenates their names as strings. #include <type_traits> #include <tuple> #include <string> template<typename types_T, int n, typename T> concept tuple_element_is = (std::is_same<typename std::tuple_element<n, types_T>::type, T>::value); template<typename types_T, int n> requires tuple_element_is<types_T, n, float> constexpr const std::string foo() { if constexpr (n < std::tuple_size<types_T>::value - 1) { return "float" + foo<types_T, n + 1>(); } else { return "float"; } } template<typename types_T, int n> requires tuple_element_is<types_T, n, int> constexpr const std::string foo() { if constexpr (n < std::tuple_size<types_T>::value - 1) { return "int" + foo<types_T, n + 1>(); } else { return "int"; } } auto t0 = foo<std::tuple<int>, 0>(); auto t1 = foo<std::tuple<float>, 0>(); auto t2 = foo<std::tuple<int, int>, 0>(); auto t3 = foo<std::tuple<int, float>, 0>(); //auto t4 = foo<std::tuple<float, int>, 0>(); -- does not compile auto t5 = foo<std::tuple<float, float>, 0>(); auto t6 = foo<std::tuple<int, int, int>, 0>(); auto t7 = foo<std::tuple<int, int, float>, 0>(); //auto t8 = foo<std::tuple<int, float, int>, 0>(); -- does not compile auto t9 = foo<std::tuple<int, float, float>, 0>(); //auto t10 = foo<std::tuple<float, int, int>, 0>(); -- does not compile //auto t11 = foo<std::tuple<float, int, float>, 0>(); -- does not compile //auto t12 = foo<std::tuple<float, float, int>, 0>(); -- does not compile auto t13 = foo<std::tuple<float, float, float>, 0>(); The instantiation t4, t8, t10, t11, t12 do not compile and produced this error: note: template argument deduction/substitution failed: note: constraints not satisfied In substitution of ‘template<class types_T, int n> requires tuple_element_is<types_T, n, float> constexpr const string foo() [with types_T = std::tuple<float, int>; int n = 1]’: required from ‘constexpr const string foo() [with types_T = std::tuple<float, int>; int n = 0; std::string = std::__cxx11::basic_string<char>]’ required from here required for the satisfaction of ‘tuple_element_is<types_T, n, float>’ [with types_T = std::tuple<float, int>; n = 1] note: the expression ‘std::is_same<typename std::tuple_element<(long unsigned int)n, types_T>::type, T>::value [with n = 1; types_T = std::tuple<float, int>; T = float]’ evaluated to ‘false’ The last note is interesting, because it is true that this expression evaluates to false, but he used the float variant for the second call. Maybe I'm using it wrong, but the compiler should re-check the requirements for each recursive call of foo and select the correct substitution, in this case int. More interestingly, it works the other way around for t3, t7 Note that calling foo<std::tuple<float, int>, 1>(); directly also works. I have tested it with both GCC and clang and they produce the same result. Any idea?
Clang gives me a very straightforward error message: error: call to function 'foo' that is neither visible in the template definition nor found by argument-dependent lookup return "float" + foo<types_T, n + 1>(); ^ note: in instantiation of function template specialization 'foo<std::tuple<float, int>, 0>' requested here auto t4 = foo<std::tuple<float, int>, 0>(); //-- does not compile ^ note: 'foo' should be declared prior to the call site constexpr const std::string foo() { The int variant of foo is not visible in the float variant, and "should be declared prior to the call site". In other words, it should be forward-declared, like this: template<typename types_T, int n> requires tuple_element_is<types_T, n, int> constexpr const std::string foo(); Demo GCC's error message is a little harder to understand, but it's still relatively straightforward when you're used to template related error messages: error: no matching function for call to 'foo<std::tuple<float, int>, (0 + 1)>()' 12 | return "float" + foo<types_T, n + 1>(); | ~~~~~~~~~~~~~~~~~~~^~ note: candidate: 'template<class types_T, int n> requires tuple_element_is<types_T, n, float> constexpr const std::string foo()' 10 | constexpr const std::string foo() { It doesn't mention any other candidate, meaning that it only considers the one it can see: the first one. Again, because the second one is not declared by that point.
74,124,663
74,124,917
How to write a custom allocator that works with MSVC
I have a simple custom allocator class to be used for std::vector, looking like this: #include <type_traits> #include <limits> #include <new> #include <vector> /** Constrains a value to be an integer which is some power of two */ template <auto value> concept powerOfTwoInt = std::is_integral_v<decltype (value)> && (value & (value - 1)) == 0; template <size_t value> requires (powerOfTwoInt<value>) constexpr size_t nextMultipleOf (size_t numElements) { return (numElements + value - 1) & -value; } template <typename ElementType, size_t alignmentInBytes> requires (alignmentInBytes >= alignof (ElementType) && powerOfTwoInt<alignmentInBytes>) class AlignedAllocator { public: using value_type = ElementType; using is_always_equal = std::true_type; constexpr bool operator== (const AlignedAllocator& other) noexcept { return true; } AlignedAllocator (const AlignedAllocator& other) = default; [[nodiscard]] ElementType* allocate (size_t nElementsToAllocate) { if (nElementsToAllocate > std::numeric_limits<size_t>::max () / sizeof (ElementType)) { throw std::bad_array_new_length (); } const auto nBytesToAllocate = nextMultipleOf<8> (nElementsToAllocate * sizeof (ElementType)); return reinterpret_cast<ElementType*> (::operator new[] (nBytesToAllocate, std::align_val_t (alignmentInBytes))); } void deallocate (ElementType* allocatedPointer, [[maybe_unused]] size_t nBytesAllocated) { ::operator delete[] (allocatedPointer, std::align_val_t (alignmentInBytes)); } }; When compiling with MSVC 19.33 and C++20 I get weird compile errors, see here. If I didn't get anything wrong, I implemented all the non-optional requirements for an Allocator, according to cppreference.com. It seems to me that the errors are somehow related to the rebind feature, which however is optional according to the document linked above. I want to keep my implementation as simple as possible, so can anyone tell me what MSVC wants me to implement here in order to solve that error? The same implementation works fine with clang.
You need a custom rebind. It's only optional if the allocator's first template argument is the element type, followed by any number of type template parameters. But you have a non-type template parameter in there. template <typename T> struct rebind { using other = AlignedAllocator<T, alignmentInBytes>; }; You also need a constructor, preferably a default constructor.
74,125,111
74,125,193
Sequencing of constructor arguments with move semantics and braced initialization?
There are many similar questions on SO, but I haven't found one that gets at this. As we all know, std::move doesn't move. That has the curious advantage of removing a potential read-from-moved-from footgun: if I call the function void f(std::vector<int>, std::size_t) with a std::vector<int> v as f(std::move(v), v.size()), it will evaluate the arguments in some order (unspecified, I think?) but std::move(v) doesn't move v, it just casts to std::vector<int>&&, so even if std::move(v) is sequenced before v.size(), v hasn't been moved from so the size is the same as if it were sequenced first. Right? I was very surprised, then, to see this logic break down in the very specific case of a braced call to a constructor, but not when I use parens for the constructor, and only when the constructor takes the vector by value. That is #include <vector> #include <fmt/core.h> struct ByValue { std::vector<int> v; std::size_t x; ByValue(std::vector<int> v, std::size_t x) : v(std::move(v)), x(x) {} }; struct ByRValueRef { std::vector<int> v; std::size_t x; ByRValueRef(std::vector<int>&& v, std::size_t x) : v(std::move(v)), x(x) {} }; template <typename T> void test(std::string_view name) { { auto v = std::vector<int>(42); // Construct with braces: auto s = T{std::move(v), v.size()}; fmt::print("{}{{std::move(v), v.size()}} => s.x == {}\n", name, s.x); } { auto v = std::vector<int>(42); auto s = T(std::move(v), v.size()); // Construct with parens: fmt::print("{}(std::move(v), v.size()) => s.x == {}\n", name, s.x); } } std::size_t getXValue(std::vector<int>, std::size_t x) { return x; } std::size_t getXRValueRef(std::vector<int>&&, std::size_t x) { return x; } int main() { test<ByValue>("ByValue"); test<ByRValueRef>("ByRValueRef"); { auto v = std::vector<int>(42); fmt::print("getXValue -> {}\n", getXValue(std::move(v), v.size())); } { auto v = std::vector<int>(42); fmt::print("getXRValueRef -> {}\n", getXRValueRef(std::move(v), v.size())); } } gcc prints ByValue{std::move(v), v.size()} => s.x == 0 ByValue(std::move(v), v.size()) => s.x == 42 ByRValueRef{std::move(v), v.size()} => s.x == 42 ByRValueRef(std::move(v), v.size()) => s.x == 42 getXValue -> 42 getXRValueRef -> 42 https://godbolt.org/z/nz3qx8nvK But then clang disagrees: ByValue{std::move(v), v.size()} => s.x == 0 ByValue(std::move(v), v.size()) => s.x == 0 ByRValueRef{std::move(v), v.size()} => s.x == 42 ByRValueRef(std::move(v), v.size()) => s.x == 42 getXValue -> 0 getXRValueRef -> 42 https://godbolt.org/z/drbYzoovd For gcc, the only surprising case is ByValue{std::move(v), v.size()} => s.x == 0. What's going on here? I've assumed that ByValue{...} turns into a "function" (cunstructor) call to ByValue(std::vector<int> v, std::size_t x), which I think means that it evaluates all of the arguments (std::move(v) and v.size()) and then calls the function. For clang, all of the by-value constructors and function calls get v into a moved-from (empty) state before the corresponding call to v.size(). What's going on? Is it that gcc evaluates right-to-left, except for in braces, and clang always left-to-right, and that if a function takes the vector by value, the argument that gets created is a vector, so it's basically saying std::vector<int>(std::move(v)), v.size(), sequenced in that order?
so even if std::move(v) is sequenced before v.size(), v hasn't been moved from so the size is the same as if it were sequenced first. Right? No, not right. The initialization of the function parameter also happens before the function is called in the context of the caller. Since your example uses a by-value std::vector parameter, not a reference, the move construction will happen in the caller and may (or may not) happen before the call to v.size(), resulting in multiple possible outcomes, which you are observing in different behavior by GCC and Clang. Using braces changes this in that initialization with braces (regardless of whether it resolves to a constructor call or aggregate initialization) is specified to evaluate all initializers and their associated effects strictly left-to-right. So there is no variation in outcome anymore. The move construction will happen before the v.size() call. You can see this in your example by both GCC and Clang agreeing on 0 as size. When you switch to a reference parameter your reasoning becomes correct and the compilers agree with you on the value of size().
74,125,454
74,126,432
I have to do a program that do a square in c++ with incremental letter
Hello and thank you for coming here. I have to do a program that will draw a number of square choosed by the user with incremental letter. For example, if the user choose 4 square, it will return : DDDDDDD DCCCCCD DCBBBCD DCBABCD DCBBBCD DCCCCCD DDDDDDD At the time being, my code look like this ; #include <iostream> using namespace std; int main() { int size; int nbsquareletter; cout << " How many square ?" << endl; cin >> nbsquareletter; size = nbsquareletter * 2 - 1; char squareletter = 'a'; for (int row = 1; row <= size; ++row) { for (int col = 0; col <= size; ++col) { if (row < col) { cout << (char)(squareletter + row - 1) << " "; } else if (row > col) { cout << (char)(squareletter + col) << " "; } /* cout << col << " "; cout << row << " "; */ } cout << endl; } } If you have any ideas to help me, don't hesitate, I'm struggling. it's been 3.5 hours. Thanks you for reading and have a good day !
Try to keep things simple. If you start write code before you have a clear idea of how to solve it you will end up with convoluted code. It will have bugs and fixing them will make the code even less simple. Some simple considerartions: The letter at position (i,j) is determined by the "distance" from the center. The distance is max(abs(i - i_0), abs(j - j_0). The center is at (i,j) = (size-1,size-1) when we start to count at upper left corner (0,0). The letters can be picked from an array std::string letters = "ABCDEFG...". i and j are in the range [0,2*size-1) Just writing this (and nothing more) down in code results in this: #include <iostream> #include <string> void print_square(int size){ std::string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; int i_0 = size-1; int j_0 = size-1; for (int i=0;i< 2*size-1;++i){ for (int j=0;j< 2*size-1;++j) { int index = std::max(std::abs(i-i_0),std::abs(j-j_0)); std::cout << letters[index]; } std::cout << "\n"; } } int main() { print_square(4); } Which produces output DDDDDDD DCCCCCD DCBBBCD DCBABCD DCBBBCD DCCCCCD DDDDDDD Your code cannot print the right output, because when row == col there is no output, and it misses the diagonal. I didnt look further than that.
74,125,618
74,125,894
Function that copies a std::vector<POD> into std::vector<char*>?
I need a function that can take a vector of any one of float, int, double or short. It should then copy all the data in that vector into a new vector of char*. Here my attempt. This is the first time I ever had to use memcpy so I don't know what I am doing. #include <vector> #include <memory> std::vector<float> vertices = { 0.0, 0.1, 0.2, 0.3, 0.4 }; std::unique_ptr<std::vector<char*>> buffer = std::make_unique<std::vector<char*>>(); template<class Type> void SetVertices(const std::vector<Type>& v) { buffer->clear(); buffer->resize(v.size() * sizeof(Type)); memcpy(buffer.get(), v, v.size() * sizeof(Type)); } int main() { SetVertices(vertices); } Here is the error message: error C2664: 'void *memcpy(void *,const void *,size_t)': cannot convert argument 2 from 'const std::vector<float,std::allocator>' to 'const void *'
There are a couple issue with your code. First is that memcpy takes a pointer to the data you want copied and to the location you want the data copied to. That means you can't pass v to memcpy but need to pass v.data() so you get a pointer to the elements of the vector. The second issue is that buffer has the wrong type. You want to store your data as bytes, so you want to store it in a char buffer. A std::vector<char*> is not a byte buffer but a collection of pointers to potential buffers. What you want is a std::vector<char> which is a single byte buffer. Making those changes gives you #include <vector> #include <memory> #include <cstring> std::vector<float> vertices = { 0.0, 0.1, 0.2, 0.3, 0.4 }; std::vector<char> buffer; template<class Type> void SetVertices(const std::vector<Type>& v) { buffer.clear(); buffer.resize(v.size() * sizeof(Type)); std::memcpy(buffer.data(), v.data(), v.size() * sizeof(Type)); } int main() { SetVertices(vertices); } Live example
74,125,987
74,233,948
Why Qt serial read data never arrives? (Qt 5.15.2, C++, Win64, MSVC2019_64)
To develop my program first without connecting two physical machines on serial port, I downloaded and used this program to simulate COM ports: https://sourceforge.net/projects/com0com/ I connected virtual COM4 to virtual COM5. It works fine. Using Br@y's Terminal program, I tested if I connect to COM4 in one Terminal instance, and to COM5 in another instance on the same computer, the data that I send on one terminal arrives in the other terminal, and vice versa. Terminal program: https://sites.google.com/site/terminalbpp/ Now let's see the problem: I used SerialPortReader class from this official Qt sample code for async serial read: https://code.qt.io/cgit/qt/qtserialport.git/tree/examples/serialport/creaderasync It connects to COM5 and sets baud rate to 9600 successfully, but no data arrives if I send something via Terminal to COM4, so: SerialPortReader runs through with no error, but after then, no matter what message I send on my Terminal instance, handleReadyRead, handleError, and handleTimeout never get called. (If I have already a terminal emulator connected to the virtual COM5 port, then connection in my C++ program fails, so indeed the open() check works fine. Also, if I try to send more than one messages to my program via the virtual COM4 port, Terminal freezes, which is a clear sign of that the previous message has not yet been read on the other side(COM5).) I have googled a lot, but have not yet found any solutions. Someone here said that it is/was a bug Qt Serial Port Errors - Data not getting read and that the problem is in qserialport_win.cpp, but even if I change that and compile my program again, nothing happens. I use the following code to create the class, but the class' content is unchanged, I use it as I found in the sample program: // Serial comm init QSerialPort serialPort; QString serialPortName = "COM5"; serialPort.setPortName(serialPortName); int serialPortBaudRate = 9600; if (serialPort.open(QIODevice::ReadOnly)) { if(serialPort.setBaudRate(serialPortBaudRate) && serialPort.setDataBits(QSerialPort::Data8) && serialPort.setParity(QSerialPort::NoParity) && serialPort.setStopBits(QSerialPort::OneStop) && serialPort.setFlowControl(QSerialPort::NoFlowControl)) { //SerialPortReader serialPortReader(&serialPort); SerialPortReader serialPortReader(&serialPort, this); } else { std::cout << "Failed to set COM connection properties " << serialPortName.toStdString() << serialPort.errorString().toStdString() << std::endl; } } else { std::cout << "Failed to open port " << serialPortName.toStdString() << serialPort.errorString().toStdString() << std::endl; } I would appreciate any help. Thanks!
Today I figured out a sketchy but working version: SerialPortReader.h #pragma once #include <QtCore/QObject> #include <QByteArray> #include <QSerialPort> #include <QTextStream> #include <QTimer> class SerialPortReader : public QObject { Q_OBJECT public: explicit SerialPortReader(QObject *parent = 0); ~SerialPortReader() override; void close(); private: QSerialPort *serialPort = nullptr; QByteArray m_readData; QTimer m_timer; public slots: void handleReadyRead(); //void handleTimeout(); //void handleError(QSerialPort::SerialPortError error); }; SerialPortReader.cpp #include <iostream> #include "SerialPortReader.h" SerialPortReader::SerialPortReader(QObject *parent) : QObject(parent) { serialPort = new QSerialPort(this); const QString serialPortName = "COM4"; //argumentList.at(1); serialPort->setPortName(serialPortName); const int serialPortBaudRate = QSerialPort::Baud9600; serialPort->setBaudRate(serialPortBaudRate); if (!serialPort->open(QIODevice::ReadOnly)) { std::cout << "Failed to open port" << std::endl; //return 1; } std::cout << "SerialPortReader(QSerialPort *serialPort, QObject *parent)" << std::endl; connect(serialPort, SIGNAL(readyRead()), this, SLOT(handleReadyRead()), Qt::QueuedConnection); // connect(serialPort, &QSerialPort::readyRead, this, &SerialPortReader::handleReadyRead); //connect(serialPort, &QSerialPort::errorOccurred, this, &SerialPortReader::handleError); //connect(&m_timer, &QTimer::timeout, this, &SerialPortReader::handleTimeout); //m_timer.start(5000); } void SerialPortReader::handleReadyRead() { std::cout << "handleReadyRead()" << std::endl; m_readData.append(serialPort->readAll()); if (!m_timer.isActive()) m_timer.start(5000); } /* void SerialPortReader::handleTimeout() { std::cout << "handleTimeout()" << std::endl; if (m_readData.isEmpty()) { std::cout << "No data was currently available for reading" << std::endl; } else { std::cout << "Data successfully received" << std::endl; //m_standardOutput << m_readData << Qt::endl; } //QCoreApplication::quit(); } void SerialPortReader::handleError(QSerialPort::SerialPortError serialPortError) { std::cout << "handleError()" << std::endl; if (serialPortError == QSerialPort::ReadError) { std::cout << "An I/O error occurred while reading" << std::endl; //QCoreApplication::exit(1); } } */ SerialPortReader::~SerialPortReader() { close(); } // Close the files, filestreams, etc void SerialPortReader::close() { // ... } ... and in my QApplication code you just need to include the .h and write this to instantiate the serial listener: SerialPortReader *serialPortReader = new SerialPortReader(this);
74,126,217
74,126,494
explicit specialization in template class error
my problem is the following, I have a template object, and in this object a method also template, for which I want to make a specialization, only the compiler always returns an error: "a declaration of model containing a list of model parameters can not be followed by an explicit specialization declaration. I would like to understand in this case if how to specialize the method, here is the code: template<typename T>class Foo { public: template<typename T2> Foo<T2> cast(void); }; template<typename T> template<typename T2> Foo<T2> Foo<T>::cast(void) { Foo<T2> tmp; std::cout << "1" << std::endl; return tmp; } template<typename T> template<> Foo< int > Foo<T>::cast< int >(void) { Foo<int> tmp; std::cout << "2" << std::endl; return tmp; } int main() { Foo<double> bar(); bar.cast<int>(); }
The problem is that we can't fully specialize the member function template without also fully specializing the class template also. This means that the correct syntax would be as shown below: template<typename T> struct CompressVector { template<typename T2> CompressVector<T2> cast(); }; template<typename T> template<typename T2> CompressVector<T2> CompressVector<T>::cast() { CompressVector<T2> tmp; //other code here return tmp; } //vvvvvvvvvv-vvvvvvvvv-------------------------------------vvv------------>made changes here template<> template< > CompressVector<int> CompressVector<int>::cast< int >(void) { CompressVector<int> tmp; //other code here return tmp; } Working demo
74,126,577
74,126,665
GLSL pass multiple arguments to shaders
I made a program that displays some textures like this it works just fine: void Texture::render(int w, int h, uint8_t *buffer) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer); glGenerateMipmap(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE0); shader.use(); unsigned int transformLoc = glGetUniformLocation(shader.ID, "transform"); glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(transform)); glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); } And this is the fragment shader: #version 300 es precision mediump float; out vec4 FragColor; in vec3 ourColor; in vec2 TexCoord; uniform sampler2D texture1; void main() { vec4 nColor = texture(texture1, TexCoord); FragColor = vec4(nColor.r, nColor.g, nColor.b, 1); } Normally this works fine, but I need to pass an argument to decide the transparency (currently it's 1 in the FragColor = vec4(...)) I've tried doing this to no avail: void Texture::render(int w, int h, uint8_t *buffer) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer); glGenerateMipmap(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE0); shader.use(); unsigned int transformLoc = glGetUniformLocation(shader.ID, "transform"); glUniform1f(transformLoc, 0.5f); glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(transform)); glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); } And simply changed the fragment shader to this: #version 300 es precision mediump float; out vec4 FragColor; in vec3 ourColor; in vec2 TexCoord; uniform sampler2D texture1; uniform float transparency; void main() { vec4 nColor = texture(texture1, TexCoord); FragColor = vec4(nColor.r, nColor.g, nColor.b, transparency); } How am I supposed to properly do this? I want to pass transparency as an additional argument.
Enable Blending (also see LearnOpenGL - Blending) and: unsigned int transparencyLoc = glGetUniformLocation(shader.ID, "transparency"); float alpha = ...; glUniform1f(transparencyLoc, alpha); I suggest multiplying the alpha channel of the texture and the value of the uniform in the fragment shader: uniform sampler2D texture1; uniform float transparency; void main() { vec4 nColor = texture(texture1, TexCoord); FragColor = vec4(nColor.rgb, nColor.a * transparency); }
74,126,891
74,126,926
Is there a way I could overload operator[] with multiple parameters?
I have the following code, and it is giving following error: binary 'operator [' has too many parameters template <typename T> struct Test { public: T operator[](int x, int y) { //... } }; Is there a way I could overload the [] operator with multiple parameters?
You need C++23 to overload operator[] with multiple parameters. Before that you can use a named function: template <typename T> struct Test { public: T get(int x, int y) { //... } }; or operator() which can be overloaded with arbitrary number of parameters. PS: If you are like me then you will wonder how that change (only one parameter allowed -> any number allowed) was possible in the presence of the comma operator. The way this is fine is that since C++23 you need parenthesis to call the comma operator (ie a[b,c] never calls operator,(b,c), while a[(b,c)] does, see https://en.cppreference.com/w/cpp/language/operator_other).
74,127,041
74,127,134
Top K Frequent Words
Given an array of strings words and an integer k, return the k most frequent strings. Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order. Example 1: Input: words = ["i","love","leetcode","i","love","coding"], k = 2 Output: ["i","love"] Explanation: "i" and "love" are the two most frequent words. Note that "i" comes before "love" due to a lower alphabetical order. i'm trying to solve this problem using Frequencies and store the most ones and loop k times to get all of them but i have a problem i can't return them as a lexicographical order upd : i solved it thanks ! class Solution { public: vector<string> topKFrequent(vector<string>& words, int k) { int n =words.size(); map<string ,int > Freq; for (int i = 0 ; i< n;i++) Freq[words[i]]++; vector<pair<string ,int >>result; vector<string>ans; for (auto it : Freq) result.push_back({it.first,it.second}); sort(result.begin(),result.end()); for (int i = 0 ; i < min(k,n);i++) ans.push_back(result[i].first); return ans; } };
you have to use compare function as a third parameter in the sort function. compare function will sort the values as you want exactly! class Solution { public: static bool cmp(pair<string ,int > &p1 , pair<string ,int > &p2) { if (p1.second == p2.second)return p1.first < p2.first ; return p1.second > p2.second; } vector<string> topKFrequent(vector<string>& words, int k) { int n =words.size(); map<string ,int > Freq; for (int i = 0 ; i< n;i++) Freq[words[i]]++; vector<pair<string ,int >>result; vector<string>ans; for (auto &it : Freq) result.push_back({it.first,it.second}); sort(result.begin(),result.end(),cmp); for (int i = 0 ; i < min(k,n);i++) ans.push_back(result[i].first); return ans; } };
74,127,419
74,134,072
Is there difference between the reinterpret_cast and the static_cast in any pointer-to-pointer conversion?
cppreference/reinterpret_cast conversion/Explanation says Unlike static_cast, but like const_cast, the reinterpret_cast expression does not compile to any CPU instructions (except when converting between integers and pointers or on obscure architectures where pointer representation depends on its type). It is purely a compile-time directive which instructs the compiler to treat expression as if it had the type new-type. Only the following conversions can be done with reinterpret_cast, except when such conversions would cast away constness or volatility. ... 5) Any object pointer type T1* can be converted to another object pointer type cv T2*. This is exactly equivalent to static_cast<cv T2*>(static_cast<cv void*>(expression)) (which implies that if T2's alignment requirement is not stricter than T1's, the value of the pointer does not change and conversion of the resulting pointer back to its original type yields the original value). In any case, the resulting pointer may only be dereferenced safely if allowed by the type aliasing rules (see below) I thought that the reinterpret_cast guaranteed the same bit pattern, and is always compile-time statement . But in the above quote, there is exception on obscure architectures where pointer representation depends on its type, and the conversion of any object pointer type T1 to another object pointer type T2 is exactly equivalent to static_cast<cv T2>(static_cast<cv void*>(expr) ). for example, int a = 10; void* b = static_cast<void*>(&a); // OK. static_cast<int*>(b) = 20; // OK. back to the original type. void* b2 = reinterpret_cast<void*>(&a); // char* b2 = static_cast<void*>(static_cast<void*>(&a) ); static_cast<int*>(b2) = 30; // also OK? because the resulting pointer is equivalent to b, so can be back to the original type. Is b resolved in run-time(can the bit pattern be changed)?. If so, is there difference between reinterpret_cast and static_cast when do any pointer-to-pointer conversion?.
Changes to the bit-pattern of a pointer aren't really quite a rare as implied, nor is the hardware necessarily quite a obscure as implied. The most common situation involves alignment requirements. A fair number of architectures require "natural alignment". That is, an object with a size of N bits also requires N-bit alignment (e.g., a 32-bit object requires 32-bit alignment). For example: // address with all the bits set in the least significant byte char *x = (char *)0xabcdef; long *y = reinterpret_cast<long *>(x); long z = *y; std::cout << (void *)y; On an x86 machine, y will usually contain exactly the bit pattern you requested (because x86 imposes few alignment requirements at the hardware level). But on something like a SPARC, MIPS or Alpha, attempting to dereference a pointer to long with the three least significant bits set will generate a processor fault. That leaves the compiler with a choice: generate a pointer that can't be dereferenced, or clear some of the bits in the pointer. At least a few choose the latter. It's certainly not guaranteed. Some will leave the value as-is, so dereferencing it just produces a processor fault. But others try to make it into a legitimate pointer to a long by zeroing the three (or so) least significant bits.
74,127,553
74,127,748
std::zoned_time on Windows Server not working
I've encountered a weird problem with std::chrono::zoned_time{}. Even oddly it works on my machine not the remote sever I'm building this app for. This simple code - witch I found there Microsoft Learn #include <iostream> #include <chrono> using namespace std::chrono; int main() { zoned_time zt("Antarctica/Casey", sys_days{2021y/September/15d}+16h+45min); sys_info si = zt.get_info(); std::cout << si; return 0; } which writes on development machine begin: 2020-10-03 16:01:00, end: 32767-12-31 23:59:59, offset: 39600s, save: 0min, abbrev: GMT+11 just dies on the deployment server. I really don't get what's being wrong here. Development machine is Windows 10 Pro, version 21H2, build 19044.2130 Deployment server is Windows Server 2016 version 1809, build 17763.3532
I do not know, but I suspect that your deployment server does not ship with the ICU library that is required for this part of C++20 to work on Windows platforms. From here: While our current implementation relies on the availability of the ICU DLL in more recent OS versions, we have plans to revisit the issue and investigate implementing a fallback for older operating systems.
74,127,942
74,137,793
Is it possible to make an array with QLists inside?
I have a 2d-array with a size of 2 x ??? so I thought I'd just use a QList like this: QList<MyClass*> arrayname[2]; But though the autofill seems to recognize this how I thought it would work, when I try to do something like arrayname[1].append(MyClassPointer); I get an error since it thinks I'm already accessing an element in the list and not the list itself. Do they just not mix well? I can neither do an array like arrayname[2][???] since of course I don't know the second dimension but making a nested list like QList<QList<MyClass*>> is just useless overkill to me since I know I'll only ever need two specific elements of the outer QList. For now I've resulted to just making two different lists QList<MyClass*> list1 and QList<MyClass*> list2 but this results in too many double code lines.
The above code was correct and works, QList<MyClass*> arrayname[2]; arrayname[1].append(MyClassPointer); is the correct syntax. The problem I was having resulted from not checking my copy/paste game and ending up calling arraynameE[1].append(MyClassPointer);, an array with a very similar name which doesn't hold a QList, thus no append can be called.
74,127,996
74,131,043
Writing a compressed buffer to a gzip compatible file
I would like to compress a bunch of data in a buffer and write to a file such that it is gzip compatible. The reason for doing this is that I have multiple threads that can be compressing their own data in parallel and require a lock only when writing to the common output file. I have some dummy code below based on the zlib.h docs for writing a gz compatible, but I get a gzip: test.gz: unexpected end of file when I try to decompress the output. Can anyone tell me what might be going wrong ? Thank you #include <cassert> #include <fstream> #include <string.h> #include <zlib.h> int main() { char compress_in[50] = "I waaaaaaaant tooooooo beeeee compressssssed"; char compress_out[100]; z_stream bufstream; bufstream.zalloc = Z_NULL; bufstream.zfree = Z_NULL; bufstream.opaque = Z_NULL; bufstream.avail_in = ( uInt )strlen(compress_in) + 1; bufstream.next_in = ( Bytef * ) compress_in; bufstream.avail_out = ( uInt )sizeof( compress_out ); bufstream.next_out = ( Bytef * ) compress_out; int res = deflateInit2( &bufstream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 15 + 16, 8, Z_DEFAULT_STRATEGY ); assert ( res == Z_OK ); res = deflate( &bufstream, Z_FINISH ); assert( res == Z_STREAM_END ); deflateEnd( &bufstream ); std::ofstream outfile( "test.gz", std::ios::binary | std::ios::out ); outfile.write( compress_out, strlen( compress_out ) + 1 ); outfile.close(); return 0; }
The length of the compressed data written to the output buffer is the space you provided for the output buffer minus the space remaining in the output buffer. So, sizeof( compress_out ) - bufstream.avail_out. Do: outfile.write( compress_out, sizeof( compress_out ) - bufstream.avail_out );
74,129,130
74,129,510
VTK face keeps rendering backwards
I am trying to render the faces of a cube using VTK 9.2. The cube's vertices are ordered like so: // 7-------6 // /| /| // 4-+-----5 | // | | | | y // | 3-----+-2 | z // |/ |/ |/ // 0-------1 +--x (Yes I know this is somewhat atypical ordering, but we're just rendering faces in VTK, so it shouldn't matter as long as we're consistent with the usage) While one of the faces works perfectly, the other consistently renders backwards regardless of how I define it. I am using the VTK_PIXEL ordering for each face. Here is the code that does the rendering: vtkGenericOpenGLRenderWindow* renderWindow = vtkGenericOpenGLRenderWindow::New(); vtkNew<vtkUnstructuredGrid> ugrid; // Create and insert vertices std::vector<std::vector<double>> vertices(8); double halfWidth = 20.0; vertices[0] = { - halfWidth, - halfWidth, - halfWidth }; // 0 vertices[1] = { + halfWidth, - halfWidth, - halfWidth }; // 1 vertices[2] = { + halfWidth, - halfWidth, + halfWidth }; // 2 vertices[3] = { - halfWidth, - halfWidth, + halfWidth }; // 3 vertices[4] = { - halfWidth, + halfWidth, - halfWidth }; // 4 vertices[5] = { + halfWidth, + halfWidth, - halfWidth }; // 5 vertices[6] = { + halfWidth, + halfWidth, + halfWidth }; // 6 vertices[7] = { - halfWidth, + halfWidth, + halfWidth }; // 7 vtkNew<vtkPoints> points; for (auto i = 0; i < 8; ++i) { points->InsertNextPoint(vertices.at(i).at(0), vertices.at(i).at(1), vertices.at(i).at(2)); } // Create faces std::vector<std::array<vtkIdType, 4>> faces; faces.push_back({ 3, 2, 7, 6 }); // +Z, works perfectly! // -Z: faces.push_back({ 1, 0, 5, 4 }); // backwards //faces.push_back({ 0, 1, 4, 5 }); // backwards //faces.push_back({ 0, 4, 1, 5 }); // backwards //faces.push_back({ 5, 1, 4, 0 }); // backwards //faces.push_back({ 4, 5, 0, 1 }); // backwards //faces.push_back({ 1, 5, 0, 4 }); // backwards //faces.push_back({ 4, 0, 5, 1 }); // backwards //faces.push_back({ 5, 4, 1, 0 }); // also backwards // Insert faces for(int i = 0; i < faces.size(); i++) { ugrid->InsertNextCell(VTK_PIXEL, 4, faces.at(i).data()); } ugrid->SetPoints(points); // Create new data mapper for this snapshot vtkNew<vtkDataSetMapper> mapper; mapper->SetInputData(ugrid); // Create new actor for this data snapshot vtkNew<vtkActor> actor; actor->SetMapper(mapper); addActorToScene(0, 0.0, actor); renderWindow->Render(); The +Z face works fantastic and looks correct. However, the other face is always backwards no matter what node order I try. This is what I see in my window: As seen there, the +Z face (3, 2, 7, 6) works great. It appears white on the outside and black on the inside. But the -Z face does not work - it appears white on the inside of the cube, and black on the outside.
It was a lighting issue, mi aculpa. I was doing the following outside of this code: vtkNew<vtkLight> light; renderWindow->AddLight(light); Once I removed that and the default lighting took over, both the inside and outside of each face appear white, so which side appears white does not indicate the direction of the face.
74,129,371
74,129,648
How to use `std::is_enum` with unnamed `enum`s?
The title is pretty much self explanatory. Here is my situation: #include <type_traits> class C1{ enum{ c1 = 3 } } class C2{ enum{ c2 = 10 } } template<class C> class C3{ void do_this(); void do_that(); void foo(){ if constexpr(std::is_enum<C::c1>::value){ do_this(); } if constexpr(std::is_enum<C::c2>::value){ do_that(); } } } If I'd try to compile this I'd get the error error: type/value mismatch at argument 1 in template parameter list for ‘template<class _Tp> struct std::is_enum’ note: expected a type, got ‘typename C::c1’ error: type/value mismatch at argument 1 in template parameter list for ‘template<class _Tp> struct std::is_enum’ note: expected a type, got ‘typename C::c2’ So hence my question: is it possible to use std::is_enum with unnamed enums?
C++11 using SFINAE You can use decltype to get the type associated with c1 and c2 and then use SFINAE as shown below . C++11 Demo: struct C1{ enum{ c1 = 3 }; }; struct C2{ enum{ c2 = 10 }; }; template<class C> class C3{ void do_this(){std::cout << "do this called" << std::endl;} void do_that(){std::cout << "do that called " << std::endl;} public: //overload for calling do_this template<typename T = C,typename std::enable_if<std::is_same<T, C1>::value, bool>::type = std::is_enum<decltype(T::c1)>::value >void foo() { do_this(); } //overload for calling do_that template<typename T = C,typename std::enable_if<std::is_same<T, C2>::value, bool>::type = std::is_enum<decltype(T::c2)>::value >void foo() { do_that(); } //overload when none of the conditions are satisfied template<typename... T> void foo(T...) { std::cout <<"ellipsis called " << std::endl; } }; int main() { C3<C1> c1; c1.foo(); //calls do_this() using #1 C3<C2> c2; c2.foo(); //calls do_that() using #2 C3<int> c3; c3.foo(); //calls the ellipsis version } See also C++ 17 demo version that uses std::enable_if_t and std::is_same_v and std::is_enum_v. C++20 using concept struct C1{ enum{ c1 = 3 }; }; template<typename T> concept enumC1 = std::is_same_v<T, C1>; struct C2{ enum{ c2 = 10 }; }; template<typename T> concept enumC2 = std::is_same_v<T, C2>; template<class C> class C3{ void do_this(){std::cout << "do this called" << std::endl;} void do_that(){std::cout << "do that called " << std::endl;} public: //overload when none of the conditions are satisfied template<typename T = C> void foo() { std::cout <<"general called " << std::endl; } //overload for calling do_this template<enumC1 T = C>void foo() { do_this(); } //overload for calling do_that template<enumC2 T = C>void foo() { do_that(); } }; int main() { C3<C1> c1; c1.foo(); //calls do_this() C3<C2> c2; c2.foo(); //calls do_that() C3<int> c3; c3.foo(); //calls the general version } C++ 20 demo
74,130,056
74,130,759
Is it possible to have a recursive typedef?
The following doesn't work. Is there some way to get around this? using Node = std::variant<Foo, Bar, std::vector<Node>>; The error produced is "error: 'Node' was not declared in this scope"
There is a simple reason why such a data structure often cannot exist. You cannot tell the size of it. For all objects the size must be clear already at compile time. But in your case this is not the show stopper. The variant or vector bring their own memory management that makes such things possible. But the way how the C++ compiler technically ensures that all sizes are known at compile time is to enforce that all types are properly defined before they are used. Therefore recursive definition like you have in your type are not legal in C++. But there is an exception (in order to allow explicitly things like your type). For structs it possible to have recursive type definition. The reason is that in OOP programming you often need such things (see the discussion here: Linked lists in C++) The solution then looks like this: struct Node{ std::variant<Foo, Bar, std::vector<Node>> value; }; It looks also incorrect. But indeed C++ accepts it. Node is an incomplete type. For structs this is accepted.
74,131,348
74,499,417
It's possible to register already defined enum for MOC?
For instance I have enum from thirdparty library: namespace Lib { enum class Foo { Bar, Baz }; }; I have tried use next wrapper namespace Qml { Q_NAMESPACE using Foo = Lib::Foo; Q_ENUMS(Foo) } with qmlRegisterUncreatableMetaObject, but its don't work for me. Can I register one in Meta Object System for using in QML, but without duplicates like: class QmlObject { Q_GADGET public: enum Foo { Bar = Lib::Bar, Baz = Lib::Baz }; Q_ENUM(Foo) }; Version of Qt is 5.15.2. Thanks.
I have found solution using the library magic_enum (at least v0.8.1, see limitations) and bit of modification in implementation of qmlRegisterType: #include <QtQml/qqmlprivate.h> #include <QtCore/private/qmetaobjectbuilder_p.h> #include <magic_enum.hpp> template<class T, class ... En> int qmlRegisterTypeWithEnums(const char *uri, int versionMajor, int versionMinor, const char *qmlName) { QML_GETTYPENAMES //! register our enums here QMetaObjectBuilder builder(&T::staticMetaObject); ([](QMetaObjectBuilder & builder) { QMetaEnumBuilder enumBuilder { builder.addEnumerator(QByteArray::fromStdString(std::string{magic_enum::enum_type_name<En>()})) }; enumBuilder.setIsScoped(magic_enum::is_scoped_enum_v<En>); constexpr auto entries = magic_enum::enum_entries<En>(); for (const auto & pair : entries) { enumBuilder.addKey(QByteArray::fromStdString(std::string{pair.second}), static_cast<int>(pair.first)); } }(builder), ...); //! *************************** QQmlPrivate::RegisterType type = { 0, qRegisterNormalizedMetaType<T *>(pointerName.constData()), qRegisterNormalizedMetaType<QQmlListProperty<T> >(listName.constData()), sizeof(T), QQmlPrivate::createInto<T>, QString(), uri, versionMajor, versionMinor, qmlName, builder.toMetaObject(), QQmlPrivate::attachedPropertiesFunc<T>(), QQmlPrivate::attachedPropertiesMetaObject<T>(), QQmlPrivate::StaticCastSelector<T,QQmlParserStatus>::cast(), QQmlPrivate::StaticCastSelector<T,QQmlPropertyValueSource>::cast(), QQmlPrivate::StaticCastSelector<T,QQmlPropertyValueInterceptor>::cast(), nullptr, nullptr, nullptr, 0 }; return QQmlPrivate::qmlregister(QQmlPrivate::TypeRegistration, &type); } Now for thirdparty enum namespace Lib { enum class Foo { Bar = 2, Baz = 4 }; }; and target Qt class namespace SomeQml { class QmlItem : public QObject { Q_OBJECT using Foo = Lib::Foo; // its important use without namespace in declaration Q_PROPERTY(Foo prop MEMBER m_val NOTIFY propChanged) ... Q_INVOKABLE handleFoo(Foo v); ... }; } just call and use on QML side as QmlItem.Bar or QmlItem.Baz as an integer : qmlRegisterTypeWithEnums<QmlItem, Lib::Foo>("my.pack", 1, 0, "QmlItem");
74,131,369
74,134,805
Pass opaque LUA data through C++
I have the following scenario: A LUA function LuaFuncA calls a C++ function CPPFunc and passes an argument Arg, which is opaque to the CPP function and could be anything (whether nil, number, userdata etc.) and cannot be assumed to be of the same type each time CPPFunc is called. LuaFuncA then terminates and only C++ code is running. After a certain amount of time (which could be anything, from milliseconds to hours) CPPFunc needs to call another LUA function LuaFuncB and pass Arg. Attempting the native solution of using lua_getpointer(L, 1) then pushing it back with lua_pushlightuserdata(L, 1) (L seems to be the same handle in both calls) results in the following error: attempt to index local 'Arg' (a userdata value). (in this case Arg was {1, 2, 3, 4} and I attempted to print Arg[2]) Thank you for any advice! EDIT: CPPFunc is a task scheduler routine. LuaFuncA basically registers LuaFuncB as a task, from which point CPPFunc need to call LuaFuncB at regular intervals, which means that the state must be either preserved or recreated before each call. EDIT 2: The program is cross-platform and must be able to run natively on both Linux and Windows, therefore platform specific calls such as fork() cannot be used.
You can use the Lua registry and reference mechanism for this. With Arg on top of the stack, do int ref = luaL_ref(L, LUA_REGISTRYINDEX);. That will pop it and save it to the registry, with ref being your key to retrieve it later. You can then save ref as you would any other int in C or C++. To retrieve Arg and push it back onto the stack, do lua_rawgeti(L, LUA_REGISTRYINDEX, ref);. If you won't need to retrieve it again, do luaL_unref(L, LUA_REGISTRYINDEX, ref); to clean up after yourself.
74,131,713
74,131,761
How to write a add function chaining?
I have questions on where to even start on this problem. The problem requires the following. // We want to create a function that will add numbers together, // when called in succession. add(1)(2); // == 3 I have never seen functions be used in such a way, and I am currently at a loss of where to start. Furthermore, I tried to do some research on parameter chaining, but this is all I could find. https://levelup.gitconnected.com/how-to-implement-method-chaining-in-c-3ec9f255972a If you guys have any questions, I can edit my code or question. Any help is appreciated.
.... way and I am currently at a loss of where to start? One way, is to start with an anonymous (unnamed) functor✱, which has operator(), that returns the reference to the this, as follows: struct { // unnamed struct int result{ 0 }; auto& operator()(const int val) noexcept { result += val; return *this; // return the instance itself } // conversion operator, for converting struct to an int operator int() { return result; } } add; // instance of the unnamed struct int main() { std::cout << add(1)(2); // prints: 3 } See a live demo ✱Read more about the unnamed structs, functors and conversion operator here: What are "anonymous structs" / "unnamed structs"? What are C++ functors and their uses? How do conversion operators work in C++?
74,132,051
74,132,940
Get function pointer from std::function that holds lambda
I want to get the raw function pointer from an std::function that has been assigned a lambda expression. When std::function is assigned a regular function, this works as expected: #include <functional> #include <iostream> bool my_function(int x) {} using my_type = bool(*)(int); int main() { std::function f = my_function; auto pointer = f.target<my_type>(); // Prints 1 std::cout << (pointer != nullptr) << std::endl; return 0; } However, when I change this example to use a lambda, it does not work: #include <functional> #include <iostream> using my_type = bool(*)(int); int main() { std::function f = [](int) -> bool {}; auto pointer = f.target<my_type>(); // Prints 0 std::cout << (pointer != nullptr) << std::endl; return 0; } Why does the second example print 0 and how could it be fixed to print 1?
Based on the OP's comment that what he wants is something he can pass as a callback parameter to a C function, here is some quick proof-of-concept code that shows how to do that with a capturing lambda. Please excuse the C-style casts but it's late and I'm tired. reinterpret_cast should work just fine. #include <iostream> #include <functional> void example_c_function (void (* callback) (void *context), void *context) { callback (context); } int main () { int i = 42; std::function <void (void)> f = [=] { std::cout << i; }; void (* callback) (void *) = +[] (void *context) { auto call_me = (std::function <void (void)> *) context; (*call_me) (); }; example_c_function (callback, (void *) &f); } Output: 42 (yay!) Live Demo Does that help, OP?
74,132,316
74,132,422
When should I decrement a variable inside of a bracket and when should I do it outside?
I was implementing a version of insertion sort when I noticed my function did not work properly if implemented the following way. This version is supposed to sort the elements as they are copied into a new array while keeping the original intact. vector<int> insertionSort(vector<int>& heights) { vector<int> expected(heights.size(), 0); int j, key; for(int i = 0; i < expected.size(); i++){ expected[i] = heights[i]; j = i-1; key = expected[i]; while(j >= 0 && expected[j] > key){ expected[j+1] = expected[j--]; } expected[j+1] = key; } return expected; } I noticed that when doing expected[j--] the function does not work as it should but when I decrement outside of the bracket it works fine. In other words, what is the difference between while(j >= 0 && expected[j] > key){ expected[j+1] = expected[j--]; } and while(j >= 0 && expected[j] > key){ expected[j+1] = expected[j]; --j; }
To answer this, we need to take a look at what order the arguments to expected[j+1] = expected[j--]; are evaluated in. Looking at cppreference's page on order of evaluation, we see the following applies for C++17 and newer: In every simple assignment expression E1 = E2 and every compound assignment expression E1 @= E2, every value computation and side effect of E2 is sequenced before every value computation and side effect of E1 In your case, this means that every value computation and side effect of expected[j--] is computed before it begins evaluating expected[j+1]. In particular, that means that j+1 will be based on the value j has after you've decremented it with j--, not the value it had before. Prior to C++17, it was indeterminate whether the left hand side or the right hand side of the assignment operation was sequenced first. This means that in C++14 and earlier, your code exhibits undefined behavior: If a side effect on a memory location is unsequenced relative to a value computation using the value of any object in the same memory location, the behavior is undefined. In this case "a memory location" is j and the decrement in j-- is unsequenced relative to the value computation j+1. This is very similar to cppreference's example of undefined behavior: a[i] = i++; // undefined behavior until C++17 In the second version of your code, the decrement to j does not take place until after the assignment has been completed.
74,132,386
74,132,585
Using std::swap_ranges with std::map
I would like to swap parts of two maps using a standard algorithm, but somehow iterators on map do not seem to be swappable. I am surely missing something. Example #include<map> #include<algorithm> auto function(std::map<int,int> m1, std::map<int,int> m2) { auto first = m1.begin(); auto last = first; std::advance(last, 3); std::swap_ranges(first, last, m2.begin()); } Error See it on compiler explorer: https://godbolt.org/z/6bn1xYTTr In file included from /opt/compiler-explorer/gcc-12.2.0/include/c++/12.2.0/bits/stl_tree.h:63, from /opt/compiler-explorer/gcc-12.2.0/include/c++/12.2.0/map:60, from <source>:1: /opt/compiler-explorer/gcc-12.2.0/include/c++/12.2.0/bits/stl_algobase.h: In instantiation of 'void std::iter_swap(_ForwardIterator1, _ForwardIterator2) [with _ForwardIterator1 = _Rb_tree_iterator<pair<const int, int> >; _ForwardIterator2 = _Rb_tree_iterator<pair<const int, int> >]': /opt/compiler-explorer/gcc-12.2.0/include/c++/12.2.0/bits/stl_algobase.h:212:16: required from '_ForwardIterator2 std::swap_ranges(_ForwardIterator1, _ForwardIterator1, _ForwardIterator2) [with _ForwardIterator1 = _Rb_tree_iterator<pair<const int, int> >; _ForwardIterator2 = _Rb_tree_iterator<pair<const int, int> >]' <source>:9:21: required from here /opt/compiler-explorer/gcc-12.2.0/include/c++/12.2.0/bits/stl_algobase.h:182:11: error: use of deleted function 'typename std::enable_if<(! std::__and_<std::__is_swappable<_T1>, std::__is_swappable<_T2> >::value)>::type std::swap(pair<_T1, _T2>&, pair<_T1, _T2>&) [with _T1 = const int; _T2 = int; typename enable_if<(! __and_<__is_swappable<_T1>, __is_swappable<_T2> >::value)>::type = void]' 182 | swap(*__a, *__b); | ~~~~^~~~~~~~~~~~ In file included from /opt/compiler-explorer/gcc-12.2.0/include/c++/12.2.0/bits/stl_algobase.h:64: /opt/compiler-explorer/gcc-12.2.0/include/c++/12.2.0/bits/stl_pair.h:715:5: note: declared here 715 | swap(pair<_T1, _T2>&, pair<_T1, _T2>&) = delete; | ^~~~ Compiler returned: 1
std::map is implemented as some sort of binary search tree, and its structure depends on each item's key never changing. Thus the type returned by *m1.begin() is std::pair<const int, int>&. Note that the first int is const. You cannot modify it. std::swap_ranges tries to swap each element of the first range with its corresponding element in the second range, but std::pair<const int, int>s can't be swapped due to the constness of their first element.
74,132,395
74,132,780
How to split string into multiple strings by delimiter
I tried to split string into 3 parts but its not working properly. i need it to be split by + and - and =. int main() { double a, b, c, x, x1, x2, d; string str, part1, part2, part3, avand, miand, azand; str = "2+4x-2x^2=0"; size_t count = count_if(str.begin(), str.end(), [](char c) {return c == 'x'; }); if (count == 2) { int i = 0; while (str[i] != '+' && str[i] != '-') { part1 = part1 + str[i]; i++; } while (str[i] != '+' && str[i] != '=') { part2 = part2 + str[i]; i++; } i++; for (i; i < str.length(); i++) { part3 = part3 + str[i]; } } }
Not knowing exactly what you are trying to accomplish, I am assuming you simply want to get the expressions that fall between the +, - and the =. If so, since the characters you want to split the string on are +, - and =, another solution is to replace those characters with a single delimiter (a space for example), and then use std::istringstream to get the parts of the string that are remaining: #include <sstream> #include <string> #include <iostream> #include <vector> int main() { std::string str = "2+4x-2x^2=0"; std::vector<std::string> parts; // replace the delimiters with spaces for ( auto& ch : str) { if ( ch == '+' || ch == '-' || ch == '=') ch = ' '; } // use std::istringstream to parse the new string std::istringstream strm(str); std::string part; while (strm >> part) parts.push_back(part); // Output values for (auto& s : parts) std::cout << s << "\n"; } Output: 2 4x 2x^2 0 Note that I use std::vector to store the parts as they are detected.
74,132,405
74,132,448
Why does TinyXml2 put XMLDeclaration at the end?
I'm using TinyXml2 v8.0.0 to create an XML buffer to send to an API. The example includes a declaration. I'm implementing this with: XMLDocument doc; doc.InsertEndChild(doc.NewDeclaration()); XMLElement* pRoot = doc.NewElement("Stuff"); doc.InsertFirstChild(pRoot); The documentation for NewDeclaration states: If the text param is null, the standard declaration is used.: <?xml version="1.0" encoding="UTF-8"?> You can see this as a test in https://github.com/leethomason/tinyxml2/blob/master/xmltest.cpp#L1637 But when I print the buffer out the declaration has been placed at the end of the buffer after a newline: <Stuff> </Stuff> <?xml version="1.0" encoding="UTF-8"?> Does anyone know why this is happening? I'd expect it to be at the start of the buffer with no newline.
Presumably, that's because you told it to put the declaration as the EndChild and the Stuff element as the FirstChild.
74,132,534
74,132,638
Creating functions for each variadic template type
I have several functions for a class which do the exact same thing but with a different type. class ExampleWrapper { public: operator T1() { ... } operator T2() { ... } operator T3() { ... } }; Is it possible to combine these into a single template parameter: class ExampleWrapper : public Wrapper<T1, T2, T3> { // does the same as above }; Bonus: Do you think this that having these functions explicitly there (perhaps with a proper name) is more readable? Edit: T1, T2, T3 are some types specified by some API.
Since we don't have reflection or template for yet, you can use variadic inheritance to compose a type with all the member function we need. Let's start with the one type case: template<typename T> struct Wrapper { operator T() { ... } }; We can now inherit multiple times from this struct using pack expansion: template<typename... Ts> struct WrapperVariadic : Wrapper<Ts>... {}; Then, inherit from that: struct HaveManyWrappers : WrapperVariadic<T1, T2, T3> { // ... };
74,132,934
74,132,998
Draw colored quad as background in OpenGL Program
I am trying to draw a quad as the background and set it to a constant color in the fragment shader. However, only one triangle of the quad gets drawn and its scaled weirdly. My vertices for the triangle are: const glm::vec3 background_vertices[6] = { glm::vec3(-1.0f, -1.0f, 1.0f), glm::vec3(1.0f, -1.0f, 1.0f), glm::vec3(1.0f, 1.0f, 1.0f), glm::vec3(1.0f, 1.0f, 1.0f), glm::vec3(-1.0f, 1.0f, 1.0f), glm::vec3(-1.0f, -1.0f, 1.0f) }; I generate a VAO and VBO for this quad with: // For background glGenVertexArrays(1, &background_vao); glGenBuffers(1, &background_vbo); glBindVertexArray(background_vao); glBindBuffer(GL_ARRAY_BUFFER, background_vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(background_vertices), background_vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), (void*)0); glEnableVertexAttribArray(0); And I finally draw it in my display function with: glUniform1i(UniformLocs::pass, BACKGROUND); glBindVertexArray(background_vao); glDrawArrays(GL_TRIANGLES, 0, 3); I also load a mesh and render that with some transparency so I have multiple shader passes (for background and for other calculations). My vertex shader takes in pos_attrib and shoots out position which gets set in: position = (pass == 0) ? pos_attrib : vec3(M * vec4(pos_attrib, 1.0)); And gl_Position is gl_Position = (pass == 0) ? vec4(position, 1.0) : PV * vec4(position, 1.0); Since my vertices are in NDC range, I don't apply any transformation to them and send them to the fragment shader as is. My fragment shader either applies a constant color or calculates the object's transparency through: switch(pass) { case 0: // Render Background fragcolor = vec4(0.9f, 0.45f, 0.25f, 1.0f); break; default: fragcolor = min(HackTransparency(), vec4(1.0)); break; } But this results in: It seems straightforward but I am not able to figure out what I'm doing wrong. How do I display a colored quad as the background? Any pointers for this will be helpful. Edit: The output now looks like:
Only one triangle is drawn because you put the same coordinates twice, but in a different order, which doesn't matter (unless you have turned on GL_CULL_FACE). To draw two triangles, you have to draw two different triangles. It's "scaled weirdly" because 0,0 is the middle of the screen, not the bottom-left corner. The bottom-left is -1,-1 and the top-right is 1,1. 0,0 is the middle.
74,133,087
74,164,978
How can I prevent linking to a specific function in a DLL, in order to maintain compatibility with an older version of that DLL?
The short version of the question: Is it possible for me to instruct Microsoft's command line C++ compiler to link against a dynamic library and tell the linker not to link against one specific function in that DLL, given the function's name (mangled or unmangled) or perhaps its ordinal, in order to preserve compatibility with earlier versions of the library's DLL that don't include that function? The long explanation: I'm developing a DLL that's a plug-in for Autodesk Maya 2020. This DLL needs to link against one of Maya 2020's dynamic libraries named OpenMayaUI. Normally plug-ins built for one major version of Maya (such as 2020) are supposed to be binary compatible with any other minor versions of that major version. For example, a plug-in built using Maya 2020.4 should still load in Maya 2020.0. However, Autodesk messed this up and introduced a single new function in Maya 2020.3's version of OpenMayaUI.dll that's not present in Maya 2020.0, Maya 2020.1, or Maya 2020.2. Consequently, if I build my plug-in so that it's linking to the version of OpenMayaUI.lib that comes from Maya 2020.3 or 2020.4, trying to load the plug-in in an earlier version of Maya 2020 will fail with the error "the specified procedure cannot be found". (And this is correct, the procedure isn't provided in the earlier versions of OpenMayaUI.dll.) However, linking against Maya 2020.0's version of OpenMayaUI.lib will produce a DLL that can be loaded by any version of Maya 2020. Unfortunately, the script that builds my plug-in needs to be able to be run on a system with any version of Maya 2020 installed, including 2020.3 and 2020.4. But I need the builds it generates to be compatible with Maya 2020.0 nonetheless. So, is it possible for me to link against the Maya 2020.4 version of OpenMayaUI.lib, but somehow tell the linker to avoid linking to the specific function in that dynamic library that's not present in the Maya 2020.0 version of OpenMayaUI? In this case I know the exact name of the function, both mangled and unmangled, and I know its ordinal in both the 2020.0 and 2020.4 versions of OpenMayaUI.dll. I'm building the plug-in using Microsoft's command line C++ compiler included with Visual Studio 2019. Edit with additional information: The offending function is a virtual member function in one of Maya's C++ classes, so even though I'm not calling it, my DLL still gets linked against it.
is it possible for me to link against the Maya 2020.4 version of OpenMayaUI.lib, but somehow tell the linker to avoid linking to the specific function in that dynamic library that's not present in the Maya 2020.0 version of OpenMayaUI? Yes. Tell the linker that OpenMayaUI.dll is to be delay loaded. Linker support for delay-loaded DLLs That way, every function that your code calls from that DLL will not be linked to statically in your plugin's IMPORTS table, but rather will be loaded at runtime via LoadLibrary() and GetProcAddress() the first time they are called. This way, your plugin has the opportunity to verify the DLL's version before calling the missing function.
74,133,293
74,133,460
compare const char * string to uint32_t value at compilation
I have version in 2 different descriptions, one as string and the other as value for example: static const char * versionStr = "03-October-2022" ; static const uint32_t versionVal = 20221003 ; How can I test if they are equal (in compile time) to make sure I didn't update one without the other? Solution in pure preprocessor smarts, I'm bound to C++98. Quite a challenge :)
You can't compare them at compile-time. But, what you can do is build up the values using preprocessor macros for the common elements, thus reducing the possibility of making a mistake, eg: #define c_day 03 #define c_year 2022 #define c_month 10 #define c_month_name October #define STRINGIFY(param) #param #define make_versionStr(y, m, d) (STRINGIFY(d) "-" STRINGIFY(m) "-" STRINGIFY(y)) #define make_versionVal_concat(y, m, d) (y ## m ## d) #define make_versionVal(y, m, d) make_versionVal_concat(y, m, d) static const char* versionStr = make_versionStr(c_year, c_month_name, c_day); static const uint32_t versionVal = make_versionVal(c_year, c_month, c_day); Online Demo
74,133,326
74,133,498
error C2672: 'std::construct_at': no matching overloaded function found error
struct FrameBufferAttachment { std::unique_ptr<Image> AttachmentImage; //std::unique_ptr<ImageView> AttachmentImageView; AttachmentType Type = AttachmentType::Color; }; struct FrameBuffer { //std::vector< FrameBufferAttachment> FrameBufferColorAttachments; FrameBufferAttachment DepthStencilAttachment; VkFramebuffer framebuffer; }; std::vector<FrameBuffer> frameBuffers; I need help with this as I can't figure out what the problem is. I get error C2672: 'std::construct_at': no matching overloaded function found but if I comment out FrameBufferAttachment DepthStencilAttachment; then the error goes away. If I change the unique pointer to a raw pointer then the error goes away too. So I must be using the unique pointer wrong. This is how I use it in code FrameBuffer frameBuffer; frameBuffers.push_back(frameBuffer); If I don't push it then no error. Any ideas?
std::unique_ptr is unique, and could not be copied. But I didn't copy anything, and what does this have to do with the error? You may wonder. Yes, here comes the tricky part of std::vector<>::push_back, it will actually copy the object instead of constructing the object on its array, therefore the object gets constructed twice. If anything, that is an unnecessary waste of time and resources. You can try to copy FrameBuffer and see that it won't be compiled: FrameBuffer frameBuffer; FrameBuffer frameBuffer_copy = frameBuffer; For most cases, prefer to use std::vector<>::emplace_back, this will construct the object on the vector itself rather than wasting time making a copy of it. See this question. Edit: As @user17732522 mentioned, this will only work for C++17 and above: FrameBuffer& frameBuffer = frameBuffers.emplace_back(); Before C++17: frameBuffers.emplace_back(); FrameBuffer& frameBuffer = frameBuffers.back();
74,133,346
74,133,382
Implementation detail inheritance?
I have structs that just contain data, a minimal example would be struct A{ int a; }; struct B{ int a; int b; }; I realized now after using these two structs that A is always should be a subset of B. Because of this, I would like to couple the structs together, so any change in A is reflected in B. The most obvious way to do this is with inheritance, so just struct B: public A{ int b; }; However, I don't want any accidental object slicing, so I also want for B to not visibly subtype A. Basically, I don't want users to know that B extends A, it should be hidden as an implementation detail. I know that the standard is "favor composition over inheritance", but that would make it so accessing the fields of B would be like "B.inner.a", which I don't really want for various reasons. Like I stated before, I want the knowledge that B is a superset of A to be an implementation detail. So far, the only things I know about C++ inheritance is that it can be public, protected, or private, but none of those modifiers help me here. Is there any language features or standard practices that can help me here?
Explicitly deleting the appropriate constructor and assignment operator will be sufficient if the goal is to prevent object slicing. struct B; struct A{ int a=0; A(); A(const B &)=delete; A &operator=(const B &)=delete; }; struct B : A { int b=0; }; B b1, b2; A a1, a2; void foo() { b1=b2; // Ok. a1=a2; // Ok. a1=b1; // Error. B b3{b2}; // Ok. A a3{a2}; // Ok. A b4{b1}; // Error } The only downside is loss of convenient aggregate initialization, that will need to be remedied with explicit constructors.
74,135,484
74,211,829
documentation of grpc versions compatibility
Is there a place that lists gRPC versions compatibility? I can't see anything like that in the documentation. I noticed that once in a while new version requires updating the auto generated files, but not always. Since it might differ in languages, I'm interested in python and C++
If you meant the compatibility between the library to generate the grpc source code from proto and the library to run it (runtime), gRPC recommend to use the same version (of both code-gen and runtime) all the time.
74,137,078
74,137,236
C++ code to overload the assignment operator does not work
I'm having some issues compiling the code I wrote which has a custom class with an overloaded =. rnumber.hpp: #include <string> class rnumber { public: std::string number; // I added this constructor in an edit rnumber(std::string s) { number = s; } void operator=(std::string s) { number = s; } bool operator==(std::string s) { return number == s; } friend std::ostream &operator<<(std::ostream &os, const rnumber n); }; std::ostream &operator<<(std::ostream &os, const rnumber n) { os << n.number; return os; } main.cpp: #include "rnumber.hpp" #include <iostream> #include <string> int main() { rnumber a = "123"; } For some reason, this does not compile with the error conversion from ‘const char [4]’ to non-scalar type ‘rnumber’ requested. This shouldn't be a problem, because rnumber has an overload for =. Why am I getting this error? EDIT: Even after adding a constructor, it doesn't work.
rnumber a = "123"; tries to initialize a with a const char*, but there is no constructor taking a const char*. You need to implement this constructor as well: rnumber(const char *s) { number = s; } There are other possibilities, mentioned on other answer and comments.
74,137,475
74,137,713
C++17 - constexpr byte iteration for trivial types
Given my prototype for a simple hashing method: template <typename _iterator> constexpr uint32_t hash_impl(_iterator buf, size_t len); Generating constexpr hashes for simple strings is pretty trivial: template <char const* str> constexpr uint32_t generate() { constexpr std::string_view strView = str; return hash_impl(str, strView.size()); } constexpr uint32_t generate(const std::string_view& str) { return hash_impl(str.begin(), str.size()); } constexpr static char str1[] = "Hello World!"; constexpr uint32_t hash1 = generate<str1>(); constexpr std::string_view str2("Hello World!"); constexpr uint32_t hash2 = generate(str2); I'd also like to generate constexpr hashes for a variety of simple (POD and trivial structs) types too. However, I'm not sure how to get the byte representation of these types in a constexpr-friendly way. My naive implementation: template <typename T, typename = std::enable_if_t< std::is_standard_layout_v<T> && !std::is_pointer_v<T> >> constexpr uint32_t generate(const T& value) { return hash_impl(reinterpret_cast<const std::byte*>(&value), sizeof(T)); } falls over because &value and reinterpret_cast<> breaks constexpr rules. I've searched for a workaround, but other answers on the site indicate that it's not possible. Worst case scenario, I can manually check for and hash specific types as so: template <typename T, typename = std::enable_if_t< std::is_standard_layout_v<T> && !std::is_pointer_v<T> >> constexpr uint32_t generate(const T& value) { if constexpr (std::is_same_v<T, int32_t> || std::is_same_v<T, uint32_t>) { char buf[] = { static_cast<char>(value >> 0), static_cast<char>(value >> 8), static_cast<char>(value >> 16), static_cast<char>(value >> 24) }; return generate(buf, 4); } else if constexpr (/* etc... */) // ... } but this falls over as soon as I try to implement this for something like a float (which has no bitwise operators) or for trivial custom types (eg, struct foo { int a; }; unless I write an extra code block for foo). I feel like I must be overlooking something simple, but I can't find any stl utility or think of any fancy template trick that would suit. Perhaps there's something in C++20 or C++23 that I'm not aware of?
It is not possible in C++17. In C++20 you can use std::bit_cast to get the object representation of a trivially copyable type: auto object_representation = std::bit_cast<std::array<std::byte, sizeof(T)>>(value); (Technically you can argue about whether or not it is guaranteed that std::array has no additional padding/members that would make this ill-formed, but in practice that is not a concern.) You can then pass the array as a pointer/size pair to the hash implementation. You should probably also add static_assert(std::has_unique_object_representations_v<T>); If the assertion fails you will have no guarantee that objects with same value will have the same object representation and same hash. Btw. std::is_standard_layout_v is not the property you need here. The property that you need to verify is std::is_trivially_copyable_v. Being standard-layout is neither sufficient nor necessary to be able to inspect and use the object representation like this.
74,137,866
74,140,136
Concept checks with invalid function calls succeed
When defining c++20 concepts to check that requirements are fulfilled by calling a constrained function the behavior is different in g++ and clang. g++ accept a type if the checking function is invalid, clang does the opposite: // constrained function template <class T> constexpr void foo1(const T& type) requires requires { type.foo(); }{} // function with required expression in the body template <class T> constexpr auto foo2(const T& type) { type.foo(); } // (x) // check for valid expression foo1 template <class T> concept checkFoo1 = requires(T t) { foo1(t); }; // check for valid expression foo2 template <class T> concept checkFoo2 = requires(T t) { foo2(t); }; Checking the concept for a type that does not have foo() as member gives unconsistent behavior: struct Test { // void foo() const {} }; int main() { static_assert(checkFoo1<Test>); // (1) static_assert(checkFoo2<Test>); // (2) static_assert(!checkFoo1<Test>); // (3) static_assert(!checkFoo2<Test>); // (4) } In clang-15: (1),(2): static assertion, (3),(4): succeed, additionally an error in (x), see https://godbolt.org/z/zh18rcKz7 g++-12: (1),(4): static assertion, (2),(3): succeed, additionally an error in (x), see https://godbolt.org/z/qMsa59nd3 In all cases, the concept check does not tell in the error messages of the static assertion why it failed, i.e., that the member function .foo() is not found. It just tells that the call to foo1() or foo2() is invalid. My questions are: What is the correct behavior and why? How to check concepts by constrained functions with detailed information about why the call to foo1() or foo2() is invalid and which constraint of these functions is not fulfilled. Sure, I could check directly for the existence of the member function foo(). But this is just an example. The goal is to emulate something like recursive concepts by recursive function calls to constrained functions. Applications are: checking that all elements of a tuple fulfill some concept, or to check concepts for all nodes in a type tree.
Calling/instantiate foo2 with invalid type would produce hard error, and not a substitution error (to SFINAE out). So checkFoo2<Test> makes the program ill-formed. As compilers try to continue to give more errors, they handle the error in some way which are not the same in given case. Both compilers are right. and then even correctly identify the problem: error: 'const struct Test' has no member named 'foo'. but following errors, (coming from the above one) are not necessary relevant/exact.
74,137,936
74,138,311
openGL triange isnt showing
GitHub code Tried to create my first triangle in openGl but got a black screen. Help find my error How can i debug such an issue in future?
Points of your geometry don't define a triangle, but a line: float vertexCoords[] = { -0.5f, -0.5f, -0.0f, -0.5f, 0.5f, -0.5f }; all have the same y-coord. Change the last point coords to: 0.5f, 0.5f. Also you missed to define VAO: GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); uint32_t buffer; glGenBuffers(1, &buffer); glBindBuffer(GL_ARRAY_BUFFER, buffer); glBufferData(GL_ARRAY_BUFFER, sizeof(vertexCoords), vertexCoords, GL_STATIC_DRAW);
74,138,232
74,138,233
Connection to valgrind embedded gdb server is failing with an error "Connection reset by peer"
I trying to follow the instruction on connecting to valgrind using gdb. Valgrind memcheck is starts properly and asks to connect using following gdb command: target remote | vgdb --pid=53181 but when I run this command, I get an error Remote communication error. Target disconnected.: Connection reset by peer what is my mistake?
It appears that error Remote communication error. Target disconnected.: Connection reset by peer. is general and may indicate invalid command as well. If you run in gdb target remote | something it will give you the same error message. It appeared for me, that extra space after | symbol was excess. Correct command was actually target remote |vgdb --pid=53181 My GDB version is GNU gdb (Ubuntu 10.2-0ubuntu1~18.04~2) 10.2
74,138,390
74,138,444
why when I create an object of a class on the stack, why it didn't delete after leaving the scoop.?
this is my class class game { private: vector<stack> stacks_; public: game(); void solve(); friend ostream& operator<<(ostream& os,const game& game); }; this is the constructor. game::game() { for (int i = 0; i < 3; i++) { stack s; stacks_.push_back(s); } cube blueCube(4,0); stacks_[0].push(blueCube); cube yellowCube(3,1); stacks_[0].push(yellowCube); cube redCube(2,2); stacks_[0].push(redCube); cube blackCube(1,2); stacks_[0].push(blackCube); } in the main function int main() { game g; cout<<g<<endl; } after creating the game class why the vector in the game class still have the object. I thought all objects that are declared like that cube blueCube(4,0); without new are on the stack and when I leave the constructor all of them will be deleted. Can anyone explain please ?
I suppose you have a using namespace std; in your code. Don't do that. In the code you posted vector can be std::vector but it could be also something else. I'll asssume it is std::vector. In your code stack cannot be std::stack (it missing a template argument) so it must be something else. So lets consider this: { stack s; stacks_.push_back(s); } s will be destroyed when it leaves the scope. push_back stores a copy of s in the vector. All fine. The copy is not affected by deleting the original (unless stack is broken in a weird way. Not respecting the rule of 3/5/0 would cause issues here). Assuming stack also stores copies of the arguments passed to push_back, the same happens as above. There is no problem with the original cubes getting destroyed. To avoid the temporaries and the copying you can use emplace_back which, given arguments for the elements constructor, constructs the elements in place.
74,138,487
74,138,772
Why does inheritance break access rights
I've been experimenting with uniform labyrinth generation, when I've found this problem. So, I've got a labyrinth_builder (lab_bui) class which provides the base for any builder algorithm. class lab_bui { protected: void say_hi() { std::cout « "hi!" « std::endl; } }; Then I create uniform_labyrinth_builder (uni_lab_bui) class inherited from lab_bui to provide base for any uniform spanning tree (labyrinth) algorithm. Uni_lab_bui has a nested class Builder which is meant to walk within the labyrinth and sometimes break walls. class uni_lab_bui : public lab_bui { protected: class Builder { public: Builder(uni_lab_bui* obj) : enclosing{obj} {} //2 overloads... WHY? void say_bye() { std::cout « "bye!" « std::endl; this->enclosing->say_hi(); } //no errors, because it's a nested class protected: uni_lab_bui* enclosing; }; }; Then I create an aldous_broder class which inherits from uni_lab_bui. Hence, it has a Builder nested class so i can create AB_Builder nested class which inherits from a Builder. Since Builder is nested, it has all access right's to all members of uni_lab_bui and hence, to all members lab_bui. Same logic applies to AB_Builder but inheritance, somewhy breaks everything and AB_Builder cannot access protected members of lab_bui. class aldous_broder : public uni_lab_bui { public: void ult() { AB_Builder b(this); b.speak(); } protected: size_t field{ 0ull }; class AB_Builder : public uni_lab_bui::Builder { public: AB_Builder(aldous_broder* obj) : Builder(obj){} void speak() { this->enclosing->say_hi(); //error because... it makes no sense - it's a nested class that can operate with protected members of aldous_broder, therefore it must be able say hi. this->say_bye(); } }; }; Sure, I can just make aldous_broder a friend of lab_bui and everything fixes up, but it makes no sense (why should I make my own grandchild my friend only so he can brush his teeth) Also, I could try reorder thing in a way so labyrinth is nested in Builder but it makes no sense too, since builder can exist only inside labyrinth, and he must stay inside it's boundaries. Also it won't really help, since enclosing class definitely has no access to protected members of nested. So, please help me make this work, without breaking encapsulation. UPD: just understood the cause of the problem. Enclosed is a uni_lab_bui pointer. In any scope, (except for uni_lab_bui scope) it can't be used to access lab_bui protected members. So now, i'm looking for a work around of this problem.
AB_Builder is a member of aldous_broder, not of uni_lab_bui, so it doesn't have access to the protected members of uni_lab_buis, just of aldous_broders. If you upcast enclosing to aldous_broder *, you can access the protected members. class aldous_broder : public uni_lab_bui { public: void ult() { AB_Builder b(this); b.speak(); } protected: size_t field{ 0ull }; class AB_Builder : public uni_lab_bui::Builder { public: AB_Builder(aldous_broder* obj) : Builder(obj){} void speak() { static_cast<aldous_broder*>(this->enclosing)->say_hi(); this->say_bye(); } }; };
74,139,893
74,140,045
Template class: operator []: 2 overloads have similar conversions
I built a simple JSON encoder/decoder in C++ (I know there are many excellent solutions for this problem out there; I'm learning the language, and it's simply a challenge to myself, and I'm not about to pretend that my solution is any good). Initially, I had the following two operator [] overloads: json& operator[](const std::string& key) { assert_type_valid(/* "object" type */); return (*object_data_)[key]; } json& operator[](size_t index) { assert_type_valid(/* "array" type */); return (*array_data_)[index]; } ... std::unique_ptr<std::unordered_map<std::string, json>> object_data_; std::unique_ptr<std::vector<json>> array_data_; And this worked great! I could do something like my_json["someKey"]["someOtherKey"][4]["thirdKey"] to access nested values. But then, because my project uses a bunch of Windows APIs that make use of both char/std::string and wchar_t/std::wstring, I wanted to make both json and wjson types, so I turned my existing json class and parser into a basic_json<CharType, StringType>. Now, the same code looks like: // Using C for CharType and S for StringType for brevity here... basic_json<C, S>& operator[](const S& key) { assert_type_valid(/* "object" type */); return (*object_data_)[key]; } basic_json<C, S>& operator[](size_t index) { assert_type_valid(/* "array" type */); return (*array_data_)[index]; } ... std::unique_ptr<std::unordered_map<S, basic_json<C, S>>> object_data_; std::unique_ptr<std::vector<basic_json<C, S>>> array_data_; Attempting to use either operator [] now results in this error: error C2666: 'basic_json<char,std::string>::operator []': 2 overloads have similar conversions could be ...::operator [](size_t) or ...::operator [](const S &) or built-in C++ operator[(__int64, const char [8]) I've tried adding a third operator [](const C* key) overload, but that hasn't made a difference. My actual question: Why has templating caused this? I'm under the impression that template types are determined at compile time, so presumably the compiler should understand what C and S are and be able to know that I'm not passing in a size_t when I do my_json["someKey"]. Also, I feel like templating has turned the once-pretty code into a huge mess. Is it ever worth simply duplicating a bunch of code in a situation like this? Like having a second parser that just works explicitly with wchar_t and std::wstring?
"Why has templating caused this?" Because class template members are only instantiated when necessary. The clue appears to be in the operator[] which you did not mention: built-in C++ operator[(__int64, const char [8]). That is to say, the compiler considers 5["someKey"]. Wait, what? Yes, in C++ that is valid. It's the same as "someKey"[5], for compatibility with C. Now how is that even relevant? Your basic_json<C, S> has an implicit conversion to int and std::string has an implicit conversion from const char [8], so the two overloads are equal. The fix: remove the implicit conversion to int.
74,140,101
74,143,056
gmock save argument string
I hope there is an easier way to do this... I need to capture the string which is passed as an argument to a mock. The mock class web_api_mock : public iweb_api { public: MOCK_METHOD( (bool), http_post, (const etl_normal_string &, const char*), (override)); }; I want to capture the char * passed to the mock as second argument. I need to construct some json structure from it, and I want to check if a certain element has a certain value. I had to spend a lot of time to get it to work, eventually copying the trick from here. This brilliant mind figured out you can rely on the gmock's Invoke. The EXPECT_CALL http_post_args args; EXPECT_CALL(_web_api_mock, http_post(etl_string_equals(url), _)) .WillOnce( DoAll( Invoke(&args, &http_post_args::capture), Return(true))); Here I am invoking all arguments of the mock to a struct which I defined as follows struct http_post_args { void capture(etl_normal_string url, const char * p) { payload = std::string(p); } std::string payload; }; And finally, I get my hands on the char * and do whatever I want afterwards. It seems awfully complicated to save an argument when it's of the type char *. My first attempt was the obvious mistake I guess many before (and after) me made: using the SaveArgPointee which will copy only the first element of the string and gives me with a string where the first character is correct, but the remaining string is filled with random mem. My second attempt was to define an ACTION_P. This "almost" worked. In the callstack I could see the string I am interested in until the very last stackframe, where the args simply seem not to be passed to the actual implementation of my custom ACTION_P. ACTION_P2(capture_string, url, payload) { /* if I break in the debugger, and go 1 stackframe up, I can see that gmock holds my string in varargs as second element But I couldn't find a way to access it here*/ } I also tried the ACTION_TEMPLATE but I am not c++ enough to understand what they are trying to explain me on gmock cookbook. So my final question: is the above working trick with http_post_args struct really "the only way" to capture a const char * being passed as an argument to a mock? If it SHOULD be possible using ACTION_P or ACTION_TEMPLATE would somebody be so kind to provide an actual working example with a const char *?
You could simply use a lambda, like so (live example): TEST(SomeTest, Foo) { std::string payload; web_api_mock m; EXPECT_CALL(m, http_post(Eq("url"), _)) .WillOnce([&](const std::string &, const char* p){ payload = p; return true; }); m.http_post("url", "foo string"); EXPECT_THAT(payload, Eq("foo string")); } No additional http_post_args or actions etc required. Of course, you could also change the payload to a const char* if you want to "capture" the raw char pointer. But be careful with the lifetime of the pointed to characters, in this case. You hinted that your real code will need to parse the payload string as json and check for a certain element. It might lead to more readable tests when you create a dedicated matcher that does this. To show a rough draft (live example): MATCHER_P(ContainsJsonElement, expectedElement, "") { const char * payload = arg; // Parse payload as json, check for element, etc. const bool foundElement = std::string(payload) == expectedElement; return foundElement; } TEST(SomeTest, Foo) { web_api_mock m; EXPECT_CALL(m, http_post(Eq("url"), ContainsJsonElement("foo string"))); m.http_post("url", "foo string"); }
74,140,269
74,194,165
Undefined symbols in .so
I develop library and trying run tests. When I run example building I got the undefined reference errors (in example one of that errors): /opt/nt/lib/libntproto2db.so: undefined reference to ntproto::variant_t::TYPE::UINT8' But, if I install same version with same commit from repository, which contains package built on the someone else machine, i have not received this error. nm tool recognizes symbol as undefined, if library built on my machine: $ nm -C -u /opt/nt/lib/libntproto2db.so | grep UINT8 U ntproto::variant_t::TYPE::UINT8 That is, if I build this library on another machine, then these symbols do not become undefined. Why? I tried: Move std::unordered_map global inline const variable, that contains values of this type from .h to .cc file, that helped, but this is bad solution. Disable optimization -O0 Check $LIBRARY_PATH, it's clear as a must be. View ld commandline during both builds (make VERBOSE=1), it is the same.
This is a distro problem, on docker it builds succesfully. Probably, one of the packages on my distro have wrong version.
74,140,665
74,155,567
Customizing MFC ribbon controls with dynamic linking
I have a VS2017 MFC C++ application which uses a ribbon based UI. Up until now I have been using the statically linked MFC libraries but now have to move to MFC in a DLL as I need Multithreaded DLL linkage /MD in order to support another third party SDK (Vulkan). One of the reasons for using statically linked MFC is that it allowed me overcome some problems in the implementation simply by including the source for the item I needed to change in my application. e.g. to use data the edit part of a combo box to select the nearest item in the drop down. This doesn't work when I use the DLL version of MFC for obvious reasons, is there any way around this? I can't simply inherit from MFC base classes as my application is building the ribbon interface from a ribbon resource file and there don't seem to be any hooks to customise this behaviour. My current thoughts for possibilities include building my own version of the MFC DLLs or simply adding the full MFC source as a sub-project and change my main project Use of MFC to Use Standard Windows Libraries. Both of these seem like nasty hacks. Edit: In response to the comment below from IInspectable, I'm not entirely sure why the current behaviour doesn't work but have some ideas. Linking the static lib version of the code, if I include my own copy of a function that occurs in the lib, the lib version never gets called (possibly never even gets linked). When linking the DLL version of MFC, my modified function never gets called. This could be because it is called by another function in the same DLL which never sees my code or it has a slightly different decorated name. My thinking is that including all the MFC source in my app and not linking any MFC in the compiler options is one brute force solution, though a pretty horrible one.
I ended up recompiling a custom version of the MFC DLL based on this project, https://www.codeproject.com/Tips/5263509/Compile-MFC-Sources-with-Visual-Studio-2019 This lets me keep my MFC modifications while also using MFC in a DLL with minimal changes to my existing project
74,141,423
74,141,513
CMake static lib error "No rule to make target"
I want to use a CMakeLists.txt file to create my library. I want to include other libraries used by my functions, but I receive the following error: make[2]: *** No rule to make target '/libs/libgsl.a', needed by 'mylib'. Stop. make[1]: *** [CMakeFiles/Makefile2:76: CMakeFiles/mylib.dir/all] Error 2 make: *** [Makefile:84: all] Error 2 My CMakeLists.txt looks like the following: cmake_minimum_required(VERSION 2.8) project(mylib) # find header & source file(GLOB_RECURSE SOURCE_C "src/*.c") file(GLOB_RECURSE SOURCE_CPP "src/*.cpp") file(GLOB_RECURSE HEADER "include/*.h") add_library(mylib ${SOURCE_C} ${SOURCE_CPP} ${HEADER} ) # includes include_directories( /include ) link_directories( /libs ) source_group("Header include" FILES ${HEADER}) source_group("Source src" FILES ${SOURCE_C}) source_group("Source src" FILES ${SOURCE_CPP}) # opencv package find_package( OpenCV REQUIRED) target_link_libraries(mylib PUBLIC opencv_highgui) # link libraries target_link_libraries(${PROJECT_NAME} PUBLIC m) target_link_libraries(${PROJECT_NAME} PUBLIC /libs/libgsl.a) target_link_libraries(${PROJECT_NAME} PUBLIC /libs/libz.a) target_link_libraries(${PROJECT_NAME} PUBLIC /libs/libpng16.a) My folder structure (of dir mylib looks like the following: mylib--build | CMakeLists.txt | include--my .h files, for static lib headers I have separate folders (e.g. include/gsl/gsl_sort.h) | libs--my static libs e.g. libgsl.a | src--my c and cpp files calling functions from the static libs I include e.g. the gsl-library to my .cpp file like this: #include "../include/gsl/gsl_sort.h"
target_link_libraries(${PROJECT_NAME} PUBLIC /libs/libgsl.a) target_link_libraries(${PROJECT_NAME} PUBLIC /libs/libz.a) target_link_libraries(${PROJECT_NAME} PUBLIC /libs/libpng16.a) Should be: target_link_libraries(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_LIST_DIR}/libs/libgsl.a) target_link_libraries(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_LIST_DIR}/libs/libz.a) target_link_libraries(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_LIST_DIR}/libs/libpng16.a) The way you have it, the libraries should exist in the folder /libs/ instead of a sub-directory of your current directory.
74,141,544
74,141,679
What is needed for this attempt at a range to pipe to a range adaptor?
I have tried to make std::optional into a range, by making an iterator that just goes to one thing then breaks: #include<ranges> #include <iostream> #include<optional> namespace maybe { template<class T> class iterator_to_nowhere { public: using difference_type = ptrdiff_t; using value_type = T; using reference = T&; using pointer = T*; using interator_category = std::forward_iterator_tag; iterator_to_nowhere(iterator_to_nowhere<T> const& other) = default; iterator_to_nowhere(T* p) : ptr(p) {}; ~iterator_to_nowhere() = default; iterator_to_nowhere<T>& operator=(const iterator_to_nowhere<T>&) = default; iterator_to_nowhere<T>& operator++() { invalidate(); return *this; } iterator_to_nowhere<T> operator++(int) { auto temp = *this; invalidate(); return temp; } reference operator*() { return *ptr; } T operator*() const { return *ptr; } pointer operator->() const { return ptr; } friend bool operator==(iterator_to_nowhere const& lhs, iterator_to_nowhere const& rhs) = default; friend bool operator!=(iterator_to_nowhere const&, iterator_to_nowhere const&) = default; friend void swap(iterator_to_nowhere<T>& lhs, iterator_to_nowhere<T>& rhs) { std::swap(lhs, rhs); } private: void invalidate() { ptr = nullptr; }; T* ptr; }; ...then implementing range things with that iterator on a derived class of std::optional template<class T> class optional : public std::optional<T> { using value_type = T; using size_type = size_t; using difference_type = ptrdiff_t; using iterator = iterator_to_nowhere<T>; using const_iterator = iterator_to_nowhere<T const>; using sentinel = iterator; public: optional() = default; optional(optional<T> const&) = default; optional(optional<T>&&) = default; optional(std::optional<T> const& val) : std::optional<T>(val) {}; optional(std::nullopt_t const& nullopt) : std::optional<T>(nullopt) {}; optional(T const& val) : std::optional<T>(val) {}; iterator begin() { return { raw() }; } const_iterator cbegin() { return { raw() }; } iterator end() { return { nullptr }; } const_iterator cend() { return { nullptr }; } size_t size() const { return size_t(this->has_value()); }; private: T* raw() { return (this->has_value()) ? (&(this->operator*())) : nullptr; } }; } I then run it in the following function: int main() { maybe::optional<int> just3(3); for (int three : just3) std::cout << three ; //prints "3"; auto adaptor = std::views::transform([](int n) {return n * 2;}); //auto six_range = just3 | adaptor; //Error C2678 binary '|': no operator found which takes a left - hand operand of type 'maybe::optional<int>' (or there is no acceptable conversion) } Building in VS2019 with the standard set as /std:c++latest, it works fine in the range-based loop but produces the given error when I try to pipe it to an adaptor. Is there something that I need to implement?
The best way to check if your range is a valid C++20 range is to check if your iterator is a valid C++20 iterator: static_assert(std::forward_iterator<maybe::iterator_to_nowhere<int>>); And when you do that you'll see that this requirement fails: /opt/compiler-explorer/gcc-trunk-20221020/include/c++/13.0.0/bits/iterator_concepts.h:538:18: note: nested requirement 'same_as<std::iter_reference_t<const _In>, std::iter_reference_t<_Tp> >' is not satisfied 538 | requires same_as<iter_reference_t<const _In>, | ~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 539 | iter_reference_t<_In>>; | ~~~~~~~~~~~~~~~~~~~~~~ Because you have: reference operator*() { return *ptr; } T operator*() const { return *ptr; } These return different types (reference is T&). Returning T& is correct, but the operator needs to be const. So: reference operator*() const { return *ptr; } Once we fix that, we have a valid input iterator. But for forward iterator, we also need default construction (which is also necessary for the sentinel). Fixing both of those things, we now have a valid range and the transform works.
74,141,621
74,141,771
range-v3 flatten the vector of struct
Is there any range-v3 way to flatten the vector (or any container) of values in struct? For example, struct Point{ double x; double y; }; std::vector<Point> points { { 0, 0 }, { 1, 1 }, { 2, 2 } }; I want to make the flattened point vector, which is std::vector { 0, 0, 1, 1, 2, 2 }.
It seems you want: auto flatten = points | std::ranges::views::transform([](const auto& p){ return std::array{p.x, p.y}; }) | std::ranges::views::join;
74,142,137
74,143,147
Polymorphism with templated class
I created a Foo class which needs to be used only as a shared pointer, so I made the constructor private to prevent client to use Foo directly: #include <memory> class Foo { public: static std::shared_ptr<Foo> Create() { return std::shared_ptr<Foo>(new Foo()); } std::shared_ptr<Foo> Copy() { return std::shared_ptr<Foo>(new Foo(*this)); } private: Foo() = default; }; I then updated Foo to use the CRTP pattern so I could have a class Bar inherit from it without having to re-define the Create() and Copy() methods: #include <memory> template <class Self> class Foo { public: template <class... Args> static std::shared_ptr<Self> Create(Args&&... args) { return std::shared_ptr<Self>(new Self(std::forward<Args>(args)...)); } virtual std::shared_ptr<Self> Copy() { return std::shared_ptr<Self>(new Self(*this)); } private: Foo() = default; }; class Bar : public Foo<Bar> {}; Then I needed to provide a non-templated FooBase interface that would provide some functions shared by all derived classes: #include <memory> class FooBase { public: virtual void DoSomething() =0; }; template <class Self> class Foo : public FooBase { public: template <class... Args> static std::shared_ptr<Self> Create(Args&&... args) { return std::shared_ptr<Self>(new Self(std::forward<Args>(args)...)); } virtual std::shared_ptr<Self> Copy() { return std::shared_ptr<Self>(new Self(*this)); } virtual void DoSomething() override { } private: Foo() = default; }; class Bar : public Foo<Bar> { public: virtual void DoSomething() override { } }; Now I also need to expose the Copy() method to the Foobar interface, but I cannot find any elegant ways to do it without changing the name for the interface (e.g. CopyBase()) #include <memory> class FooBase { public: virtual void DoSomething() =0; // Expose Copy method by using a different name. virtual std::shared_ptr<FooBase> CopyBase() const =0; }; template <class Self> class Foo : public FooBase { public: template <class... Args> static std::shared_ptr<Self> Create(Args&&... args) { return std::shared_ptr<Self>(new Self(std::forward<Args>(args)...)); } virtual std::shared_ptr<FooBase> CopyBase() const override { return Copy(); } virtual std::shared_ptr<Self> Copy() { return std::shared_ptr<Self>(new Self(*this)); } virtual void DoSomething() override { } private: Foo() = default; }; class Bar : public Foo<Bar> { public: virtual void DoSomething() override { } }; This code works, but I feel that there must be a better way to do this. I exposed my thinking process in details as I suspect that the flaws might be in the design, so I'm wondering if anyone could help me gain a different perspective on this issue. Thanks for your time!
covariant return type is only possible with regular pointer or reference, not with smart pointer. Additional issue with CRTP is that class is incomplete, so covariance cannot be used neither. The traditional way is indeed to split the clone in 2 part, a virtual one (private) and a public (non-virtual) one, something like: template <typename Derived, typename Base> class Clonable : public Base { public: template <class... Args> static std::shared_ptr<Derived> Create(Args&&... args) { return std::shared_ptr<Derived>(new Derived(std::forward<Args>(args)...)); } std::shared_ptr<Derived> Clone() const { return std::shared_ptr<Derived>(static_cast<Derived*>(vclone())); } private: // Cannot use covariant-type `Derived*` in CRTP as Derived is not complete yet Base* vclone() const override { return new Derived(static_cast<const Derived&>(*this)); } }; And then class FooBase { public: virtual ~FooBase() = default; virtual void DoSomething() = 0; // Expose Copy method by using a different name. std::shared_ptr<FooBase> Clone() const { return std::shared_ptr<FooBase>(vclone()); } private: virtual FooBase* vclone() const = 0; }; class Bar : public Clonable<Bar, FooBase> { public: void DoSomething() override { } }; Demo
74,142,872
74,143,464
Boost Sockets message exchange c++
I am currently trying to create a server to client connection to send XML documents. It appears that it is possible to send these documents after serializing them. My plan is to establish a connection, send one message from client to the server (a list of filters) and then send N messages from the server side when a message meets the filters criterias. However, before getting to that, I wanted to try a simple implementation of this using only strings to see how it works and to get a better understanding of the boost asio library. I then implemented my server part: #include <iostream> #include <thread> #include <queue> #include <chrono> #include <array> #include <boost/asio.hpp> int main() { const int BACKLOG_SIZE = 30; unsigned short PORT = 3333; // Endpoint and io_service creation boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address_v4::any(),PORT); boost::asio::io_service ios; boost::asio::ip::tcp::acceptor acceptor(ios, ep.protocol()); // Binding to client acceptor.bind(ep); acceptor.listen(BACKLOG_SIZE); boost::asio::ip::tcp::socket socket(ios); // accepting connection (blocking process) acceptor.accept(socket); std::cout << "Binded" << std::endl; // Receiving data from client boost::asio::streambuf sb; boost::system::error_code ec; while (boost::asio::read(socket, sb, ec)) { std::cout << "received: " << &sb << "\n"; if (ec) { std::cout << "status: " << ec.message() << "\n"; break; } } // Sending data to client socket.send("Filters received!"); } and my client part: #include <boost/asio.hpp> #include <iostream> int main() { std::string raw_ip_address = "127.0.0.1"; unsigned short port_num = 3333; std::string FILTER = "ATL"; try { // Endpoint creation boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address::from_string(raw_ip_address), port_num); boost::asio::io_service ios; // Creating and opening a socket. boost::asio::ip::tcp::socket sock(ios, ep.protocol()); // Connecting a socket. sock.connect(ep); // Sending data to server std::cout << "Connected to " << raw_ip_address << " Port: " << port_num << std::endl; sock.send(boost::asio::buffer(FILTER)); boost::asio::streambuf sb; boost::system::error_code ec; // Receiving data from server while (boost::asio::read(socket, sb, ec)) { std::cout << "received: " << &sb << "\n"; if (ec) { std::cout << "status: " << ec.message() << "\n"; break; } } } // Overloads of asio::ip::address::from_string() and // asio::ip::tcp::socket::connect() used here throw // exceptions in case of error condition. catch (boost::system::system_error& e) { std::cout << "Error occured! Error code = " << e.code() << ". Message: " << e.what(); return e.code().value(); } return 0; } I first started with only sending the filters from the client to the server and it all worked well. However when I tried adding the response from the server to the client, it caused an error which I don't really understand: error As anyone faced this issue and know how to solve it? Is it even possible to establish a connection like that where both side of the socket can send messages as they want (as I said the idea will be to have the server sending N messages coming from another application, after receiving the filters list). Thanks for your help.
First problem: string literals are not a buffer (or buffer sequence). You need to describe the buffer, e.g. like so: std::string response("Filters received!"); socket.send(boost::asio::buffer(response)); There are many ways. E.g. not using a temporary, you could use a string view literal: socket.send(boost::asio::buffer("Filters received!"sv)); Second problem: while (boost::asio::read(socket, sb, ec)) { This cannot work, because you meant sock, not socket (which exists, but is ::socket, type int(&)(int,int,int). That said, it's not very useful to read-to-EOF in a while loop, since the loop will always break with EOF (or another error). Finally, because currently, client will never close the socket until a response is received, there will be an indefinite waiting of both programs. Consider a partial shutdown: sock.send(asio::buffer(FILTER)); sock.shutdown(tcp::socket::shutdown_send); Here are client and server combined Live On Coliru #include <boost/asio.hpp> #include <iostream> namespace asio = boost::asio; using asio::ip::tcp; using boost::system::error_code; using namespace std::string_view_literals; static const std::string raw_ip_address = "127.0.0.1"; static const std::string FILTER = "ATL"; static const int BACKLOG_SIZE = 30; static const uint16_t PORT = 3333; int main(int argc, char**) { asio::io_service ios; asio::streambuf sb; error_code ec; try { if (argc > 1) { // client tcp::endpoint ep({}, PORT); tcp::socket sock(ios, ep.protocol()); sock.connect(ep); // Sending data to server std::cout << "Connected to " << sock.remote_endpoint() << std::endl; sock.send(asio::buffer(FILTER)); sock.shutdown(tcp::socket::shutdown_send); read(sock, sb, ec); std::cout << "received: " << &sb << "\n" << "status: " << ec.message() << "\n"; } else // server { tcp::acceptor acceptor(ios, tcp::v4()); acceptor.bind({{}, PORT}); acceptor.listen(BACKLOG_SIZE); tcp::socket sock(ios); acceptor.accept(sock); std::cout << "Accepted " << sock.remote_endpoint() << std::endl; read(sock, sb, ec); std::cout << "received: " << &sb << "\n" << "status: " << ec.message() << "\n"; sock.send(asio::buffer("Filters received!"sv)); } } catch (boost::system::system_error& e) { std::cout << "Error occured! Error code = " << e.code() << ". Message: " << e.what() << "\n"; return 1; // e.code().value() not very useful, as the category is lost } } Run and build with e.g. g++ -std=c++20 -O2 -Wall -pedantic -pthread main.cpp -isystem /usr/local/include/ ./a.out& sleep 1; ./a.out client Prints e.g. Connected to 127.0.0.1:3333 Accepted 127.0.0.1:50816 received: ATL status: End of file received: Filters received! status: End of file
74,143,350
74,143,427
Simplest case of currying with a lambda is illegal
The textbook functional programming introduction example "return a function with a curried parameter" in C++ does not compile for me: // return a function x(v) parameterized with b, which tells if v > b bool (*greater(int))(int b) { return [b](int v) { return v > b; }; } It says that identifier b in the capture [b] is undefined. I know that I'm being naive here, but where is my error? EDIT: as @some-programmer-dude pointed out correctly, the function signature is wrong. greater is a function accepting an int b returning ( a pointer * to a function accepting an (int) returning a bool ). // return a function x(v) parameterized with b, which tells if v > b bool (*greater(int b))(int) { return [b](int v) { return v > b; }; } This of course does not remove the original question which all three replies answered correctly.
You say that greater is a function taking an unnamed (anonymous) int argument, and return a pointer to a function taking an int argument with the name b. The part (int b) is the argument list for the returned function pointer. To solve that specific problem use bool (*greater(int b))(int) instead. Because function pointers are so complicated, they are usually hidden behind type-aliases: using greater_function_type = bool(int); greater_function_type* greater(int b) { ... } As for the problem that lambdas with captures can't be used as C-style function pointers, use std::function as return type instead: using greater_function_type = std::function<bool(int)>; greater_function_type greater(int b) { ... } Note that it's not returning a pointer anymore. Since the C++14 standard you can use automatic return-type deduction with the keyword auto: auto greater(int b) { ... } If you need to store the returned objects, for example as a class member variable, you need to use std::function<bool(int)> for that. Also be careful when using names like greater in conjunction with using namespace std; (which is a bad habit), because of std::greater.
74,144,375
74,144,479
Why a class can see the private members of a parameter class?
Note that class x and y are two separate entities and you can not see their private data members from outside of their bodies. It is known that from int main() I can not see the private member of class x or y. My question in the following code in line 22: Why class x can see the private members of class y ? (note here I am sending class y as reference not as a copy) isn't the referenced class y should be protected from strangers like class x ? Note that the function getForeignNumber(const Player &r) inside class x is not a friend to class y! #include<iostream> class Account{ private: int number{ } ; public: Account(int numberValue) :number{numberValue} { std::cout<<"constructor is called"<<std::endl; } int getLocalNumber() { return this->number; } int getForeignNumber(const Account &r) { return r.number; // line 22 } }; int main() { Account x{1}; Account y{2}; std::cout<<"get local number="<<x.getLocalNumber()<<std::endl; std::cout<<"get foreign number x ="<<x.getForeignNumber(x)<<std::endl; std::cout<<"get foreign number y="<<y.getForeignNumber(y)<<std::endl; std::cout<<"Hello world"<<std::endl; return 0; }
First of all, you are confusing instances of a class with the class. x and y are two instances of the same class Account. Your analogy isnt sound. Two instances of the same class aren't "strangers". They can access all the internals of each other. Thats how access works. From cppreference: All members of a class (bodies of member functions, initializers of member objects, and the entire nested class definitions) have access to all names the class can access. A local class within a member function has access to all names the member function can access. In other words, access is per class not per instance. If x would not be able to access ys private members it would be impossible for example to write a copy constructor (without getter methods, which would be silly). PS: By the way, "see" is the wrong word. There are certain circumstances where you can "see" that there is a private member from outside of the class, you just cannot access it. One such situation is when the name of a private method shadows that of a publicly inherited method https://godbolt.org/z/Kzf5KWv4W. Hence, even colloquially "see" is the wrong word for access.
74,144,453
74,144,520
Add functionality to a pure virtual function in C++?
I wish to have a pure virtual function, but I need to guarantee that all implementations of it include some bookkeeping. Here is a workaround that achieves what I want, but it is clunky. Is there a better approach? If not, is there a naming convention for a function like actually_do_it()? class A { public: virtual void do_it() final { bookkeeping(); actually_do_it(); } protected: virtual void actually_do_it() = 0; private: void bookkeeping() {} }; class B : public A { void actually_do_it() {} }; ... B b; b.do_it();
Is there a better approach? If not, is there a naming convention for a function like actually_do_it()? "better" is purely subjective unless you define what "better" means. You approach is widely accepted and known as the Template Method Pattern (see eg https://en.wikipedia.org/wiki/Template_method_pattern). I have seen it more commonly used when a method consists of several steps and the derived classes can customize the individual steps, but your use case is just as valid.
74,145,213
74,157,360
Cannot get an OEX program to run on Android
I'm trying to implement an OEX (open engine exchange protocol) chess program for Android. This has been discussed at What is OEX (Open Exchange Protocol?) and can I call such APK from my app? earlier. The java-part of the program runs fine, yet the native library always segfaults. Even with something simple as #include <stdio.h> int main(int argc, char *argv[]) { printf("Hello, world!\n"); return 0; } I noticed one thing to be different: the libstockfish.so library seems to be linked to /system/bin/linker while my library is not linked at all? file libs/x86_64/libstockfish.so: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /system/bin/linker64, BuildID[sha1]=b690a6bb7630099c6618950a9e1604850f1de836, stripped file libs/x86_64/libDog.so libs/x86_64/libDog.so: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, BuildID[sha1]=93a9d3635eef9fc0f2140a87956db9ac80459993, stripped What is it that I could be doing wrong? I'm using the ndk-build script: jni/Application.mk: APP_ABI := all APP_PLATFORM := 21 #NDK_TOOLCHAIN_VERSION := 4.9 APP_STL := c++_shared APP_CPPFLAGS += -frtti APP_CPPFLAGS += -std=c++17 jni/Android.mk LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := Dog LOCAL_SRC_FILES := test.cpp LOCAL_STRIP_MODE := none LOCAL_PRELINK_MODULE := false LOCAL_CPPFLAGS += -std=c++17 -Wall -DVERSION=\"0.8\" -DNAME_EXTRA=\"\" -fexceptions -Wno-c++11-narrowing -fPIC -pie -fPIE LOCAL_LDLIBS += -shared LOCAL_LDFLAGS += -fPIC -pie -fPIE -Wl,--entry=main,-dynamic-linker=/system/bin/linker LOCAL_CPP_FEATURES := exceptions include $(BUILD_SHARED_LIBRARY) Any ideas?
Found the solution: apparently the idea is to trick the packaging system by creating a regular binary and renaming it to e.g. libstockfish.so. Then the board-programs can happily import them and play chess with them.
74,145,807
74,148,681
Child from fork() gets terminated before end of process
Quick question about processes in C/C++. When I use fork() to create two processes in my main, on my child process I am calling an extern API to get a vector of bools and send it through a pipe to the parent, but when I call the API he kills right away the child process without sending the vector through the pipe first. Why do you guys think this might be happening? The code is something like this : //main.cpp #include "main.hpp" int main(){ pid_t c_pid = fork(); if(c_pid == 0) { std::cout << "Code From here implements Child process"<< std::endl; API::Api_Get_Method(); // Child dies here std::cout << "Finish Child process " << std::endl; std::exit(EXIT_SUCCESS); // But should die here } else{ wait(nullptr) std::cout << "Code From here implements Parent process Id : " << std::endl; std::cout << "Finish Parent process " << std::endl; } } //main.hpp namespace API{ void Api_Get_Method(){ // Do stuff // Print the result of the Stuff } } ```
with your else statement, it runs "wait(nullptr)" for all pids that are not zero, which is not necessarily only the parent. Also, if you do wait(nullptr) in the parent, it will wait until all child processes have terminated before continuing (which is good because they're not left orphanated). Children from fork() ideally should be terminated because if they aren't, they're stuck as allocated space not being referenced by a parent in the processes tree. This eats RAM and slows the thread that it's on. Given a lot of these, one might have to restart their system. In short, it's just memory and thread resource allocations.
74,145,841
74,145,867
I'm Getting error while trying to delete heap allocated int
#include <iostream> class TEST { public: int* a = new int; TEST(int x) : a(&x) { } ~TEST() { delete a; } }; int main() { { int i = 2; TEST T(i); } std::cin.get(); } I tried to heap allocate integer in a TEST class and then delete it but when I'm calling delete a in TEST class destructor I'm getting error in file called delete_scalar.cpp and I have no idea what does it mean and how to fix it. Where's the problem?
TEST(int x) : a(&x) { } This code is causing undefined behavior. It is making a point at a local int that goes out of scope immediately afterwards, leaving a as a dangling pointer to invalid memory. a is never pointing at dynamic memory (the new expression in the declaration of a is ignored when a is initialized in the constructor's member initialization list). That is why the delete fails later. To do what you are attempting, you need to either: move the new into the initialization list, eg: int* a = nullptr; TEST(int x) : a(new int(x)) { } Or, if you want to keep using new in the declaration of a, then you can assign the value of that int from inside the constructor's body instead of in its initialization list, eg: int* a = new int; TEST(int x) { *a = x; }
74,145,888
74,145,996
why not have a virtual ptr per class?
It seems that it's sufficient to have a virtual ptr per class even when a class is derived from two base classes. For example, #include <iostream> class A{ public: void* ptr; virtual void printNonOverride() { std::cout << "no override" << std::endl; } virtual void print() { std::cout << "hello world!" << std::endl; } }; class C { public: double c; virtual void cFunc() { std::cout << "C"; } }; class B : public A , public C { }; int main() { A a{}; std::cout << sizeof a << std::endl; C c{}; std::cout << sizeof c << std::endl; B b{}; std::cout << sizeof b << std::endl; } The output for this is 16 16 32 which makes sense because sizeof B = sizeof A + sizeof C. However, this seems a little bit inefficient. Why does B need to allocate 2 virtual pointers? Why not just allocate one that refers to B's own virtual tables? Then the sizeof B will be 24. Thank you!
Because you can do B b{}; C* pc = &b; pc->cFunc(); and pc has to point to something that looks like a C - including starting with a virtual pointer suitable for a C. B and A can share the same virtual pointer, because the compiler can make it so that B's virtual table begins the same way as A's virtual table (and then has some extra stuff at the end). But it can't do this for both A and C at the same time. B's virtual table can't begin the same way as A's and begin the same way as C's. That's not possible.
74,147,088
74,147,134
What does "[&]" mean in C++ lambda?
I am reading to an open source project. I am not able to understand what this snippet does ? EXPORT Result LoaderParse(LoaderContext *Cxt, Context **Module, const char *Path) { return wrap([&]() { return fromloa(Cxt)->parse(std::filesystem::absolute(Path)); }, [&](auto &&Res) { *Mod = toAST((*Res).release()); }, Cxt, Module); } template <typename T, typename U, typename... CxtT> inline Result wrap(T &&Proc, U &&Then, CxtT *...Cxts) noexcept { if (isC(Cxts...)) { if (auto Res = Proc()) { Then(Res); return 0; } else { return 1; } } else { return 2; } } Can anyone explain me what does [&] do in this case?
[&] alongside with [=] denotes a capture-default policy for the given lambda: & (implicitly capture the used automatic variables by reference) and = (implicitly capture the used automatic variables by copy). For your particular case it means that two first closures (arguments) passed to the wrap function can access all variables in the given context (Cxt, Module and Path) by reference. There are other side effects a capture list may introduce, e.g. the lambda has deleted copy-assignment operator in C++20 and cannot be casted into a function pointer.
74,147,166
74,147,427
C++ duplicate virtual function override when derived class overrides member variable
I have a base class and many derived classes, defined in the following way: class BaseClass { public: virtual ClassType getClassType() {return classType;} private: ClassType classType = BaseType; } class DerivedClass: public BaseClass { public: ClassType getClassType() override {return classType;} private: ClassType classType = DerivedType; } There are many similar derived classes of the same base class that share a similar structure. I have a generator that keeps generating BaseClass objects, and each time I will call x.getClassType() to know its class type, then use dynamic_cast to cast it to the corresponding derived class. The problem is, I have to write the same getClassType() function over and over again in each of the derived classes. Is there anyway to just write the function only once, and each class will return their corresponding value of classType when called from a BaseClass*?
I will call x.getClassType() to know its class type, then use dynamic_cast to cast it to the corresponding derived class. If you know what an object's type is, you can use static_cast instead of dynamic_cast. On the other hand, if you use dynamic_cast, you can get rid of getClassType() altogether, as you can just query the object whether it matches a given type. Is there anyway to just write the function only once, and each class will return their corresponding value of classType when called from a BaseClass*? You only need one classType member, in the BaseClass, you don't need to repeat that member for each class. As such, you can remove virtual from getClassType(), and then give BaseClass a constructor parameter to assign the classType member. That way, DerivedClass can then pass its type to the BaseClass constructor, eg: class BaseClass { public: BaseClass(ClassType classType = BaseType) : classType(classType) {} ClassType getClassType() { return classType; } private: ClassType classType; }; class DerivedClass : public BaseClass { public: DerivedClass() : BaseClass(DerivedType) {} }; The downside to this approach is if you want to derive another class from DerivedClass later on, you will have to give DerivedClass a similar constructor to passed along the new class's type, eg: class BaseClass { public: BaseClass(ClassType classType = BaseType) : classType(classType) {} ClassType getClassType() { return classType; } private: ClassType classType; }; class DerivedClass : public BaseClass { public: BaseClass(ClassType classType = DerivedType) : classType(classType) {} }; class AnotherClass : public DerivedClass { public: AnotherClass() : DerivedClass(AnotherType) {} }; Otherwise, you can leave virtual on getClassType(), and get rid of the classType member altogether. Simply have BaseClass and DerivedClass (and any subsequent classes) override getClassType() to directly return their respective type, eg: class BaseClass { public: virtual ClassType getClassType() { return BaseType; } }; class DerivedClass : public BaseClass { public: ClassType getClassType() override { return DerivedType; } }; class AnotherClass : public DerivedClass { public: ClassType getClassType() override { return AnotherType; } };
74,147,421
74,208,158
How to emit event in a Turbo Module on iOS
I'm following the guide here to create a Turbo Module in React Native. https://reactnative.dev/docs/next/the-new-architecture/pillars-turbomodules How do you emit events on iOS? The documentation only shows how to call a native function from React, but not how to emit an event from the Turbo Module. For Android, you get a ReactApplicationContext object, which lets you create an emitter like this using the context object. private val emitter = context.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java) emitter.emit(eventName, eventArray) How do you do the same thing on iOS?
To emit events to RN from iOS you should make your own emitter class that is inherited from RCTEventEmitter and then init it on JS side with NativeEventEmitter and add listeners for needed events with addListener: EventEmitter.h #import <React/RCTEventEmitter.h> @interface EventEmitter : RCTEventEmitter + (instancetype)shared; @end EventEmitter.m #import "EventEmitter.h" // Events static NSString* onMyEvent = @"onMyEvent"; // Variable to save the instance static EventEmitter* eventEmitter = nil; @implementation EventEmitter /// Exposing "EventEmitter" name to RN RCT_EXPORT_MODULE(EventEmitter); // Called from RN - (instancetype)init { if (self = [super init]) { eventEmitter = self; } return self; } + (BOOL)requiresMainQueueSetup { return NO; } + (instancetype)shared { return eventEmitter; } // List of supported events - (NSArray<NSString *> *)supportedEvents { return @[onMyEvent]; } @end How to call: NSDictionary* body = @{@"message" : @"Hello Emitter!"}; [EventEmitter.shared sendEventWithName:@"onMyEvent" body:body]; RN/JS import { ... NativeEventEmitter, NativeModules, } from 'react-native'; import type EmitterSubscription from 'react-native'; class EventHandler extends React.Component { eventsSubscription: EmitterSubscription; componentDidMount() { const eventEmitter = new NativeEventEmitter(NativeModules.EventEmitter); this.eventsSubscription = eventEmitter.addListener('onMyEvent', event => { console.log(event.message); // Prints "Hello Emitter!" }); } componentWillUnmount() { this.eventsSubscription.remove(); } ... };
74,148,448
74,148,571
How to give argument to write registry?
I wrote the code below to edit a registry value: #include <windows.h> #include <string.h> int main(int argc, char* argv[]) { HKEY hkey = NULL; const char* evtwvr = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Event Viewer"; const char* exepath = "file://C:\\Users\\MrUser\\Desktop\\temp.exe; LONG rgdt = RegOpenKeyEx(HKEY_LOCAL_MACHINE, (LPCSTR)evtwvr, 0 , KEY_WRITE, &hkey); if (rgdt == ERROR_SUCCESS) { RegSetValueEx(hkey, (LPCSTR)"MicrosoftRedirectionUrl", 0, REG_SZ, (unsigned char*)exepath, strlen(exepath)); RegCloseKey(hkey); } return 0; } It simple edits the registry key and writes the exe path as a value. But I want to do it like this: myprogram.exe C:\Users\User\MrUser\temp.exe and pass the input parameter into the registry value.
Simply replace exepath with argv[1] instead. Also, your LPCSTR casts are unnecessary. And you need to add +1 to strlen() because REG_SZ requires the string's null terminator to be written. #include <windows.h> #include <string.h> int main(int argc, char* argv[]) { if (argc < 2) return 1; const char* evtwvr = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Event Viewer"; HKEY hkey = NULL; LONG rgdt = RegOpenKeyExA(HKEY_LOCAL_MACHINE, evtwvr, 0, KEY_SET_VALUE, &hkey); if (rgdt == ERROR_SUCCESS) { RegSetValueExA(hkey, "MicrosoftRedirectionUrl", 0, REG_SZ, (LPBYTE)argv[1], strlen(argv[1])+1); RegCloseKey(hkey); } return 0; } That being said, since you want to use a command line parameter to edit the Registry, you could just use Windows built-in reg command instead, eg: reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Event Viewer" /v MicrosoftRedirectionUrl /t REG_SZ /d "C:\Users\User\MrUser\temp.exe" /f