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.
usin... | 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()
{
... | 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, th... |
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); // EX... | 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. ... | 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 func... |
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 on... | 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 <<... |
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. D... |
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() = defau... | 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 ... |
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_... | 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 u... |
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... | 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 ... |
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... | 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() + off... |
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 re... |
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 onl... | 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... |
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 ... | 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 ... |
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 ... | 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=loop... |
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_lis... | 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_t... |
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 ... | 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... |
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 err... | 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 sh... |
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> ... | 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 << st... |
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<i... |
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 spe... |
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*/
} /*Devi... | 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 = "";
... | 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
it... |
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 quest... | 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... |
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 is... | 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 poi... |
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... |
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... |
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... | 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... | 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 ... |
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 ... | 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 d... |
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 ... | 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), c... |
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) {
un... | 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> wi... |
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... | 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 fun... |
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<... | 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... |
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) w... | 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>>... |
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... | 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 ... |
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 ... | 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... |
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?... | 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 f... | 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<<th... | 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 does... |
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 perform... | 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_A... |
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 s... | 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 ... |
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 (wha... | 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 <sstrea... |
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); ... | 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::tup... |
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)> && (va... | 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 als... |
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... |
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::vect... |
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>
u... | 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 ... |
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> verti... | 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 t... |
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 i... | 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);
~Ser... |
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 lik... | 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> templa... |
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);
s... | 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 t... |
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 h... |
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"]... | 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.se... |
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... | 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 a... |
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"... | 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 inve... |
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 ... | 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 QLis... |
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... | 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 ... | 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 fa... |
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){
... | 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;}
... |
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 t... |
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 S... | 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(... |
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++ c... | 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... |
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,... |
.... 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;
... |
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_fu... | 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 <iost... |
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> expecte... | 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 @= E... |
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::... | 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... |
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 ... | 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... |
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 ... | 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, T... | 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:
tem... |
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),
... | 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 ... |
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 compatibil... |
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... |
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 prepro... | 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 STRING... |
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;
FrameB... | 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 construct... |
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 mo... | 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=... |
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 operat... | 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 ha... | 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/... |
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 req... | 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... |
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)... |
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... | 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 w... |
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... | 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:
{
... |
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_... | 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_Bui... |
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[](con... | "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... |
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 ... | 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", "fo... |
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 o... | 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 ... | 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: *** [Makefil... | 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} P... |
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_... | 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/iterat... |
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() {
... | 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 li... |
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 me... | 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::buff... |
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 [... | 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 poi... |
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 ... | 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 (bodi... |
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 vo... |
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 se... |
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... | 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... | 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() idea... |
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... |
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 initialize... |
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 << ... | 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 the... |
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(... | [&] 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... |
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;}
priv... |
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 qu... |
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 ge... | 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
+ (instancety... |
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 = ... | 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 = "SO... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.