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 |
|---|---|---|---|---|
65,897,241 | 65,897,242 | 'non-type partial specialization' when implementing a templated member function | In the following code i go on to create a struct with a templated get-function, and then a templated struct.
#include <iostream>
struct MyStruct
{
int a;
template<typename T> T getA();
};
template<typename T>
T MyStruct::getA<T>()
{
return static_cast<T>(a);
}
template<typename T>
struct MySt... | For whatever reason the template type is not repeated within a name of the member function during the implementation, which is different to the way the name of the class/structure is handled. The correct way to implement it is:
template<typename T>
T MyStruct::getA()
{
return static_cast<T>(a);
}
Here getA<T> ... |
65,897,259 | 65,897,333 | Why in a C++ template, declaring a vector<T> member variable as static will produce linker error but inline static will not? | I cannot explain the following (using C++20 rules)
//FooTemplate.h
template<typename T>
class FooTemplate {
private:
static std::vector<T> t; //linker error.
//inline static std::vector<T> t; --> will not produce linker error
//static T t; -->this works also with the appropriate changes in the following code
... | Static members must be defined (initialized) outside their class.
Simply write in your implementation:
template<class T> std::vector<T> FooTemplate<T>::t = [some initializer];
EDIT: You do not actually need to explicitely initialize them (unless they are objects of a class without a default constructor), but you do ne... |
65,897,845 | 65,897,858 | Process finished with exit code -1073741515 when calling GLEW functions | I've written a basic OpenGL program in C++ which just opens a window. I'm now trying to draw a triangle, but I'm having some issues calling GLEW functions. This is my code with just OpenGL:
#include "include/glew.h"
#include "include/glfw3.h"
int main()
{
GLFWwindow* window;
if (!glfwInit())
return -1... | You have to Initialize GLEW. Call glewInit right after making the OpenGL context current:
glfwMakeContextCurrent(window);
if (glewInit() != GLEW_OK)
return 0;
In addition, you have to make sure that the DLL files can be found at runtime. Add a path to the Windows path environment variable or place the DLL files i... |
65,898,522 | 65,903,619 | Adjacency Matrix and Adjacency List of connected Graph | Suppose in a social media network:
N is friends with K, P, U, X
X is friends with N, A, B and C
U is friends with A, B and N
A is friends with P, U and X
B is friends with X and U
P is friends with K, N and A
K is friends with P, N and M
M is friends with C, N and K
Solve the following problems in c++
a. Write... | The solution to problems a and b is the following:
#include <iostream>
using namespace std;
class Graph {
int v;
int** adj;
public:
Graph(int v);
void addEdge(int start, int e);
void printMatrix();
void nonConnected(int start);
};
Graph::Graph(int v)
{
this->v = v;
adj = new int*[v];
... |
65,898,663 | 65,917,316 | Set Home position for stepper motor STM32 | I have a Nucleo-IHM01A1 motor driver to drive a motor mounted with a spindle. The spindle has a limited length with an object in between. As the motor spins, the object moves along the spindle.
How can I set the Home position of the motor such that every time I run the program on the MCU, the Home position is set when ... | Unfortunately, the mechanical and electrical setup you describe does not actually allow automatic home calibration in a proper way.
Stepper Motors are used, as name suggests, to perform steps. They are not capable of absolute positioning on their own. If you need absolute positioning, you will have to either set your h... |
65,898,918 | 68,735,577 | Delete column in 2D std::vector depending on comparison of 2 rows in same column in C++ | I have a 2D std::vector < std::vector <double> > array consisting of three rows and an unknown number of columns. I would like to delete any column where the value of row 0 > row 1. Here is my effort:
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
inline void printArray (const std::v... | The following approach deletes the desired columns "in place" instead of copying. The strategy is adapted from How to delete column in 2d vector, c++
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
inline void printArray (const std::vector< std::vector< T > >& key_array) {
for (in... |
65,899,029 | 65,901,982 | Is the dynamic initialization of the non-local variable thread-safe | I have following code in one of the source file of my application:
// file1.cpp
#include <memory>
static auto global_variable = std::make_unique<int>(123);
int get_global_variable() { return *global_variable; }
Let assume that my application has some threads which call the get_global_variable. Is the initialization ... |
[basic.start.dynamic]/4 It is implementation-defined whether the dynamic initialization of a non-local non-inline variable with static storage duration is sequenced before the first statement of main or is deferred. If it is deferred, it strongly happens before any non-initialization odr-use of any non-inline function... |
65,899,128 | 65,899,395 | Change Perlin noise algorithm to work with continuous procedural generation | Right now I have a perlin noise function where I pass a buffer of seeds and another buffer which the function fills with the noise values. I am using this to procedurely generate the heights of the vertices in a terrain. The problem is right now the terrain is limited to the size of the buffer but I want to have it con... | Presumably this is tied in to a "map reveal" mechanism?
A common technique is to generate overlapping chunks and average them together. As a simple example, you generate chunks of 2*nWidth by 2*nHeight. You'd then have 4 overlapping chunks at any XY pos. At the edge of the map, you'll have a strip where not all chunks ... |
65,899,232 | 65,899,557 | Using templates on Container type in C++ | I am trying to write a generic function to compute barycenter of a bunch of numbers,
I found the following one but I am unable to use it:
template <typename Container>
auto getBarycenter(Container &&cont)
{
decltype(cont[0]) res(0.0f);
for (auto &v : cont)
res += v;
return res / static_cast<float>(c... | Given the information you provided, there's at least one problem in that snippet showed.
decltype(cont[0]) evaluates to (potentially non-const) lvalue reference to the containers values. This can be fixed using std::decay_t (or std::remove_cvref, if you have access to c++20) which will remove the "reference-ness" and c... |
65,899,372 | 65,899,499 | Can't add element into container<T> with emplace new if T has explicit constructor | I am writing a fixed size container type, with placement new.
When I was testing it I figured it out my "emplace_back()" like function does not compile if the type T has explicit ctor.
Here is a code sample (with missing delete call, etc):
#include <iostream>
template <typename T>
struct TestType
{
explicit TestTyp... | You're specifying TestType<int> as template argument for std::forward as std::forward<TestType<int>>(args)..., means you're forwarding arguments as TestType<int>. The argument being passed is tried to be converted to TestType<int> implicitly, which doesn't work because the converting constructor is marked as explicit.
... |
65,899,529 | 65,901,558 | Undeclared Identifier Error when using function returning pointers to functions (C++ on Visual Studio) | I wrote the following function:
typedef float (*flIntPtr)(char);
flIntPtr c(int i) {
flIntPtr pt = &b;
return pt;
}
float b(char c) {
....//do something
}
Then visual studio reported that b is an undeclared identifier.
I have go through the examples of possible causes to C2065:undeclared identifier below:
Com... | Your compiler tries to understand your code by digesting it from the top to bottom. This means that you need to have a inverted tree like structure (meaning that you need to have all the dependencies of a dependent somewhere on the top of it). When you don't have it, the compiler will flag an error.
int main()
{
fo... |
65,899,782 | 65,900,953 | Qt Linux to Windows transition: Error in macro substitution | I have a Qt project (Version 5.14.2), which is building just fine under Linux. Now I would like to provide it on Windows as well. However, I have some trouble getting it built. The following error is thrown:
Error: Cannot find = after : in macro substitution.
And then a line in the makefile. When I go to the line ther... | Nevermind, found a solution. The problem was burried somewhere completely else in the code. I was using some git shell commands:
exists ($$PWD/.git) {
GIT_DESCRIBE = $(shell git --git-dir $$PWD/.git --work-tree $$PWD describe --always --tags)
GIT_BRANCH = $(shell git --git-dir $$PWD/.git --work-tree $$PWD rev... |
65,899,973 | 65,901,357 | c++ segmentation fault and Trace/breakpoint trap when using Dynamic memory allocation | I am practicing Dynamic memory allocation in C++. I wanna enter some word which length is less than 10, and when I enter "-1", it will print the word I have entered before.
But when I enter more than three words, it will give me an Trace/breakpoint trap or segmentation fault. I use gdb-peda to check my code, it said "d... | First of all, try not to use using namespace std;.
I have also found a memory leak in your code. You allocate the word pointer every iteration but did you make sure to delete it when you get to the next iteration? What you need to do is, delete the word buffer at the end of the iteration. Plus you also have two variabl... |
65,899,979 | 65,900,223 | How to trim last four character from the input in bash shell? | I intend to automate compile and run process in C++, I wrote the following code as compile-run.sh
#! /bin/bash
clang++ $1.cpp -o $1.out && ./$1.out
I put this compile-run.sh in /usr/local/bin for global usage,
and when I type the command compile-run.sh XXX.cpp, it intend to compile and run the specified cpp file. But ... | well, an ugly way could be by using something like:
#! /bin/bash
filename=$1
temp="${filename%%.cpp}"
clang++ $temp.cpp -o $temp.out && ./$temp.out
another way, if you want to trim the last 4 characters whatever the last part is:
#! /bin/bash
filename=$1
temp="${filename::-4}"
clang++ $temp.cpp -o $temp.out && ./$temp... |
65,900,112 | 65,906,067 | Recover moved element after failed move insertion/emplace in std::unordered_map | I fill a std::unordered_map using the insert or emplace methods and the move semantics. When a key clash occurs the element is not inserted in the map but the moved element is erased anyway:
#include <unordered_map>
#include <iostream>
int main(){
std::unordered_map<int, std::string> m;
m.insert(std::make_pair... | If using C++17 features is an option, try_emplace will only move the arguments if the key doesn't already exist in the map.
Otherwise, you can have your own version to get (functionally) the same effect, by combining find and emplace (or insert).
Note that this will likely be less efficient than the try_emplace impleme... |
65,900,218 | 65,900,367 | Template that measures elapsed time of any function | I want to create a template function that measures the elapsed time of any other function.
What I did until now:
using TimeDuration = std::chrono::nanoseconds;
std::tuple<FuncReturnType, TimeDuration> measureTime(Func func, Args&&... args)
{
auto start = std::chrono::high_resolution_clock::now();
auto ret = fu... | You might do something like:
template <typename Func, typename ...Args>
auto measureTime(Func func, Args&&... args)
{
using FuncReturnType = decltype(func(std::forward<Args>(args)...));
const auto start = std::chrono::high_resolution_clock::now();
if constexpr (std::is_same_v<void, FuncReturnType>) {
... |
65,900,252 | 65,900,421 | Is there a c++ std solution to filter and reduce without creating a copy? | I want to find the minimum element of a filtered list. In Python, I would write:
it = (x for x in [1, 8, 4, 3] if x % 2 == 0)
min(it, default=None)
I hoped that the c++ equivalent would read something like:
const std::vector<int> array {1, 8, 4, 3};
const auto arr_end = std::end(array);
auto it = std::find_if(std::be... | There isn't an answer in std as of C++17. In C++20 you can use std::ranges::filter_view, outside of std you can use ranges::filter_view from the range-v3 library, which was the demonstration implementation for the C++20 ranges proposal.
auto filtered = ranges::filter_view(array, [](int value) { return value % 2 == 0; }... |
65,900,281 | 65,952,993 | Why program linked against Qt 5.9 cannot run under Qt 5.6? | I have a program built under Qt 5.9 environment. When I copy the program to a server that is installed with Qt 5.6, the program cannot start, with the following error:
./myapp: /usr/lib64/libQt5Core.so.5: version `Qt_5.9' not found (required by ./myapp)
But /usr/lib64/libQt5Core.so.5 does exist, which is a link to lib... | Minor releases of the Qt libraries only maintain backward binary and source compatibility, meaning that an older executable will work as is with a newer library (see details here).
So if you intend to deploy your program on a server with Qt 5.6, it should be compiled with Qt 5.6 or older, and as long as you don't use f... |
65,900,901 | 65,901,103 | Template type deduction in parameter and return type | in our current code base we have code that looks something like the below (this is of course a simplified version):
#include <map>
#include <string>
#include <iostream>
using namespace std;
// General template function to convert an enum to a string, given a converter-container
// The converter-container is either a ... | Just deduce the type of second, something like:
template<typename Container, typename Index,
typename NoMatchType=decltype(std::declval<typename Container::value_type &&>().second)>
auto toString(Container&& names, Index&& index,
const NoMatchType &noMatch=NoMatchType{})
(You can also use NoMatc... |
65,901,693 | 65,903,005 | Should i use dynamic_cast here? | Well, i have next code:
#include <type_traits>
#include <iostream>
#include <string>
#include <list>
#include <functional>
class base_main
{
public:
virtual ~base_main()
{
}
// some methods
};
class base_1 : virtual public base_main
{
// some methods
};
class base_2 : virtual public base_main
{
... | It is hard to tell what design you should choose as this heavily depends on the overall structure of the application.
Generally, I would avoid having a function with the signature virtual void object_created( base_main* o ) in which you dynamically cast to base_* and work on that directly in this function. Because the... |
65,901,849 | 65,902,548 | Can I use `distance` as my class member variable name? | It would be ok to define a class like this (ignore its implmentation):
class MyEngine {
private:
int* params;
int param_len;
public:
void set_params(int* _params, int _len);
float get_result(); // relies on `distance` member
float distance; // people can modify this
};
However, if using vec... | Well, one is MyEngine::distance, and the other is std::distance. They're different names. This is the whole point of scopes.
There is only a problem if you use the unqualified name distance and leave the compiler to figure it out, but if that's not going to work then it'll be because the type of the one chosen doesn't ... |
65,902,072 | 65,902,159 | Where Object Is Allocated When Created By Another Object That Was Allocated On Heap? | class Foo {
int num;
};
class Bar {
public:
Bar() {
Foo f1;
}
};
int main() {
Bar* b = new Bar();
return 0;
}
In the code above, I create an instance of Bar (b) on the heap.
In the constructor of Bar, an instance of Foo (f1) is created. Since b is created on the heap, and f1 is temporary, ... | The storage of the object pointed to by b — that is, the object of type Bar — is allocated on the heap.
However, f1 isn’t part of that object. Instead, it’s a local object that’s created when a function is called (the function being the constructor to Bar, but that’s irrelevant). And local objects are all allocated on ... |
65,902,416 | 65,902,586 | Initializing a class object as wrong type | I have this code and I'd like to ask - how is it possible to initialize a class object with new int() without getting an exception?
When I print the value of the object it prints junk but I still don't understand how this assignment is possible.
What exactly happens when you use new int(value)? doesn't it create space ... | You are probably looking for explicit keyword:
Without explicit, the compiler will try implicit conversion between types using the constructor:
class Test
{
public:
Test(int){}
};
Test t = 42;
If this is not supposed to happens, then you can use explicit (I personally recommend to use it by default on each non-copy s... |
65,902,697 | 65,903,556 | Use Template in GTEST (Googletest) | I know. The headline is not perfekt. Perhaps I fund a better Headline later.
I have a Problem with GTEST with template.
(Yes I know. The code make no sense. It is a sample).
I have the following template:
template<typename T>
struct MY_VALUE{};
template<>
struct MY_VALUE<uint8_t>{
static const uint8_t v... | The problem is with the fact that assertion engine of GTEST requires reference. To have reference - variable needs to be defined:
template<>
struct MY_VALUE<uint8_t>{
static const uint8_t val = 8;
};
// this line is missing
// Note: do not put it in header - if you have multiple files project
const uint8_t MY... |
65,902,941 | 65,902,964 | How can a vector be declared in C++ with no errors? | I'm trying to learn C++, but I've been stuck for a long time because I don't know how to solve the following issue. I have changed from CodeBlocks to CLion hoping for escaping from this issue, but it was not helpful.
I have this code:
int main()
{
vector<int> vect(10);
}
And the errors are the following:
error: 've... | You need the include the corresponding header
#include <vector>
Also that class is within a namespace (std:: in this case), so you need to add that as well
int main()
{
std::vector<int> vect(10);
}
|
65,903,259 | 65,903,643 | C++ Call functions based on enum values | I have this code
class Foo {
private:
enum class Heuristic {
ONE,
TWO,
THREE
};
Heuristic h;
void select();
};
void Foo::select() {
if (h == Heuristic::ONE)
selectONE();
else if (h == Heuristic::TWO)
selectTWO();
else
selectTHREE();
}
v... |
To avoid the conditional check in select() [...]
A simple way to avoid all conditional checks (hidden or otherwise) in select() could be to create an array of pointers to your functions. You then look the function up by using its current Heuristic value (which must start at 0 and not have any gaps). If the Heuristic ... |
65,903,910 | 65,904,548 | Why can this derived class be constructed with `{}` and not with `()` on C++17? | In this example, C++17 can construct a Derived class using the Base class's constructor using {}, but not ().
This also works on C++20 for GCC and Clang, but not for MSVC.
Why can I constuct the Derived class this way? Is it safe?
I have looked through the additions and changes in C++17 and can not find what changed to... | Here's a quick rundown of the situation:
Base is implicitly convertible from an int.
Base is not an aggregate, since it has a user-provided constructor.
Derived is not convertible from an int (implicitly or otherwise), since base-class constructors are not inherited unless you explicitly inherit them (which you didn't... |
65,903,959 | 65,904,752 | Trying to recreate this piece of code from JS in C++ | I've watched a course on Dynamic Programming and the instructor solved the problem like this, in JS.
I understood the logic, but now I have to write it in C++. Here's his code:
I'm trying to transition to C++ but I'm thrown off by some errors:
std::vector<int> howSum(std::vector<int> numbers, int target)
{
if (tar... | Unlike JavaScript, C++ variables cannot hold value of null. NULL is not a replacement for it - this is just a fancy way to write 0. Starting from C++17, the standard library has a template for a nullable type: std::optional (see cppreference). Its syntax partly imitates pointers.
Also, push_back() does not return the r... |
65,904,317 | 65,904,843 | Reset Total Variable | I am working on a blackjack-like program. I initially generate a random pair of cards and store the total of the numbers. If the user wishes to, he or she can choose to play again. When I compile the program and choose the play again option (enter "n" to the first prompt), the total remains the same as the two previous... | Problem solved: the declaration and initialization of num1, num2 and total
should be moved into the first do-while loop.
Here's the correct code, also with edited indentations:
/*
Cortez Phenix
The 25th of January, 2021
CS10B, Mr. Harden
Assignment 2.1
This program uses loops and variables, allowing the user to play a... |
65,904,463 | 65,906,382 | runtime error: reference binding to null pointer of type 'int' (merge function) | I am trying to solve the problem of finding the median of two sorted arrays on Leetcode but I am getting the following error:
Line 811: Char 16: runtime error: reference binding to null pointer of type 'int' (stl_iterator.h).
Can someone help me solve this error?
class Solution {
public:
double findMedi... | Declare num3 as vector<int>nums3(nums1.size() + nums2.size());. Also in your merge second parameter needs to be nums1.end()
|
65,904,542 | 65,904,760 | print 2D char array with void function | I have a 2D char array and I am trying to print it with a void function but it is showing an error
#include <bits/stdc++.h>
void printt(int x, int y, char[][] matrix){
for(int i = 0; i< x; i++){
for(int j = 0; j<y; j++){
std::cout<<matrix[i][j];
}
}
}
int main(){
int n = 4,m = 4;
char mat[n][m];
for(in... | you can not call the function printt(mat); like that, the function requires 3 parameters, you are just giving 1...
is defined as
void printt(int x, int y, char[][] matrix)
so you have to do instead:
printt(n, m, mat);
|
65,904,892 | 65,905,282 | Second FOR loop is being skipped | I am not getting any compile-time errors, but whenever i run the program the second FOR loop gets skipped and the program stops. i put a cout after it and that executed, but the second for loop was still skipped.
#include <iostream>
using std::cout;
int main()
{
int numbers[5];
for(int i; i < 5; i++)
{
... | When you write
int i;
That declares an int named i without initializing it. Its value is said to be indeterminate. There is not much you can do with an indeterminate value, for example
int x = i;
invokes undefined behavior. When your code has ub then almost anything can happen. You could get no output at all, or som... |
65,905,010 | 65,905,064 | Does shallow copy call member objects' constructors? | Assuming i have this code:
class A {
public:
int x;
A(){}
A(const A& a){} //copy constructor
operator= (const A &a){...}
};
class B {
public:
A a;
B(){}
};
int main() {
B b;
B c = b; //shallow copy
B d;
d = b; //shallow assignment
}
Will the shallow copy\assignment call member A... | Then the answer is yes, the copy constructor will be called, but the assignment operator will not.
The copy constructor will be called because the defaulted copy constructor is called, but the assignment operator is not. The defaulted assignment operator will call the defaulted copy constructor, and the defaulted copy ... |
65,905,302 | 65,905,547 | How do you tell CMake to statically link to a library in a package found with find_package? | I am building a library from source and an executable that depends on the library. The library depends on a third-party library, libjpeg, which I would like to handle via static linking. libjpeg is installed on my system. I can see the .a file at /usr/lib/x86_64-linux-gnu/libjpeg.a(I am building on Ubuntu.)
When proces... | Before anything, you should fix your script:
target_link_libraries(my_library PRIVATE JPEG::JPEG)
You have to give the imported target name to target_link_libraries.
That being said, no, not directly. find_package itself does nothing of the sort, it simply looks for the correct script and calls it. Thus the actual beh... |
65,905,498 | 65,905,706 | 2 Dimensional array initializer list exception | [Exeption]
Hello guys,
I'm trying to make an initializer_list constructor for 2D array.
Any Help, please?
.......................
Matrix(int row,int col,const std::initializer_list<double>& list)
{
rows = row;
cols = col;
std::initializer_list<double>::iterator it;
arr = new double* [rows];
/*d... | You did not allocate enough memory. Also note that you probably do not want to reset k in every iteration and there are ranged-based loops if you want to do something on the entire container:
//correct allocation
int n = 0;
int k = 0;
for (auto const& number : list) {
arr[k][n] = number;
n++;
if (n == col) {
... |
65,905,581 | 65,905,763 | Overload operator '<<' without output streaming intentions | I'm new to operators overloading and I'm facing this challenge:
I have this class Ticket and i'm creating 2 objects Ticket, ticket1 and ticket2. Each ticket has a number of suitcases, I store that ids into a vector named id_suitcases.
Now I want to be able to add several suitcaseID's to that vector using operator <<
eg... | Your operator<< cannot chain:
bool operator << (int suitcaseID)
{
for (auto suitcase : id_suitcases)
if (suitcaseID == suitcase)
{
return false;
}
id_suitcases.push_back(suitcaseID);
return true;
}
Consider that
ticket1 << 455 << 73 ... |
65,905,610 | 65,906,372 | How to use SFINAE to enable a certain std::initializer_list constructor only for suitable types | Below you find a stripped down, reproducible example of what I'm trying to accomplish. My use-case is a custom container class template. The class has a constructor, taking a std::initializer_list of the element type. For the case that the container holds elements of the type std::unique_ptr<OwnedType>, I want to enabl... | You are just missing one detail.
SFINAE is only possible on the immediate context, which does not include the template parameters from the class. Only the template parameter from the method.
One way of solving this is to use an extra template parameter in the method, that default to T.
template <typename U = T, typenam... |
65,905,636 | 65,905,664 | University exercise, i'm trying to understand what this means | const int N = 5;
struct array_str {
int array[N];
unsigned int size;
};
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
return 0;
}
void readArray(array_str& v){
for (<#initialization#>; <#condition#>; <#increment#>) {
<#statements... | is the parameter of the type array_str passed as reference under the name v when you call the function readArray
|
65,905,785 | 65,905,887 | Name look-up fails - c++ namespaces | Could you explain why namespace look-up fails in that code?
namespace B {
namespace C {
int i;
}
}
namespace A {
namespace B {
void foo() {
// why does not much A::B::C
B::C::i = 3;
}
}
}
Yes, I know ::B::C::i works because we indicates global namespace but I am curious why look-up does not search outsi... | Within the namespace ::A::B, the unqualified lookup for B finds the namespace ::A::B rather than finding the namespace ::B. And there is no name ::A::B::C, so the qualified lookup for C within the found ::A::B fails.
|
65,905,841 | 65,905,908 | How to overload operator<< with a function as parameter (like endl for cout)? | How to overload an operator<< with a function as parameter, like std::endl does for std::cout?
In my project, I need to do this. For example, in the following code:
CSampleClass test;
test << CSampleClass::foo; // foo is function
I write code as following but it causes an error:
In the class header file:
CSampleClass&... | In order to use foo with overload
CSampleClass& operator << (CSampleClass& (*pf)(CSampleClass&));
it needs to be a non-member function or a static member function.
|
65,905,923 | 66,575,580 | Member access rules for friend of derived class, where the naming class is the base class | All standard references below refer, unless noted otherwise, to N4861 (March 2020 post-Prague working draft/C++20 DIS).
Background
According to [class.access.base]/5:
If a base class is accessible, one can implicitly convert a pointer to a derived class to a pointer to that base class [...].
Meaning the following ex... | Actually, the section [class.protected#1] is an additional clause for [class.access.base#5] when the nominated member is a protected member of the naming class to which R occurs at a member or friend of a derived class.
According to class.access.base#1,
the non-static protected member of N is accessible as a private me... |
65,905,940 | 65,906,141 | reading/writing from ostringstream changes original data | Inside a test, I write a given value to an ostringstream. After that, I try to evaluate if the correct value was written. However, it seems that the original value I wrote into the stream is changed later on while reading from it.
I reduced my problem to the following code:
#include <sstream>
#include <cassert>
#includ... | std::copy() does not do what you think it does in this situation. It is just a wrapper for a logical loop that copies individual elements from one container to another. You are essentially telling it to copy 2 individual chars from data_str into a uint16_t[2] array, except that you don't actually have such as array, ... |
65,906,452 | 65,912,321 | TensorflowLite C API input buffer layout for multidimensional tensor | I'm having a TensorFlow model that takes inputs of shape [1, 128, 1024, 2]. I'd like to run inference on this model with the TensorflowLite C API.
The sample code from the tensorflow/lite/c/c_api.h shows how to feed input into the model:
std::vector<float> inputBuffer(1 * 128 * 1024 * 2);
// populate input buffer
// .... | You don't need to flatten that array, just changed inputBuffer.data() to the pointer of your data.
The input tensors in TFLite model has the shape information (1, 128, 1024, 2). So It will be able to understand your array correctly.
|
65,906,803 | 65,907,560 | if code is using "implicit boolean conversions".can valid c++03 code, break in c++11? | With addition of change in c++11
change:Change: Specify use of explicit in existing boolean conversion operators
(https://timsong-cpp.github.io/cppwp/n4618/diff.cpp03.input.output)
can valid c++03 code break in c++11?
struct abt {
public:
abt(int a, double b){}
abt(int a){cout<<"int"<<endl;}... | Even if your abt would have only an explicit converion if(is) would be fine in C++11, because the condition of an if is a context where explicit conversions are "implicit". From cppreference:
In the following contexts, the type bool is expected and the implicit
conversion is performed if the declaration bool t(e); is ... |
65,906,971 | 65,907,388 | create struct from JSON object in c++ / Arduino | I have a big JSON config file on an SD on my Arduino
"general": {
"dhcp": true,
"macAddress": [500,500,500,500,500,500],
"destinationIP": [500,500,500,500],
"serverHostname": null,
"interval": 5,
"commaDecimalSeperator": true,
"baudrate": 115200
},
"networ... | The ArduinoJson library has a nifty online assistant tool to help generate some of that, e.g.:
// char* input;
// size_t inputLength; (optional)
StaticJsonDocument<768> doc;
deserializeJson(doc, input, inputLength);
JsonObject general = doc["general"];
JsonArray general_macAddress = general["macAddress"];
int genera... |
65,907,591 | 65,965,751 | CDialog: Why SetParent(this) change the visual Style? |
I create a Non modal CDialog in a CView derived class m_wndTestDlg.Create(CTestDlg::IDD, this); and Show/Hide and move the Dialog with the following code
h File:
class CTestView : public CView
{
:
CTestDlg m_wndTestDlg;
:
}
cpp File:
void CTestView::OnInitialUpdate()
{
CView::OnInitialUpdate();
m... | If the ulterior motive for SetParent is to keep the dialog in front of the view then the following might work (or it might not, depending on UI specifics). If, however, the reason is to clip the dialog to the parent view, then this won't help, though it still attempts to explain why.
Main issue here is an inconsistency... |
65,907,680 | 65,924,982 | Singletons that outlive main | The "magic static" singleton approach is generally quite effective:
T& instance() {
static T inst;
return inst;
}
In a threadsafe way, it creates the T on first call and that object lives until program shutdown. However, if this is a logging object, and if there are background threads that outlast main, this c... | The reason the other questions don't provide solutions is that it impossible to do usefully in most circumstances. Allowing threads to live past main is difficult to write and maintain. Some of the rules are:
[basic.start.term/4] If a function contains a block variable of static or thread storage duration that has bee... |
65,907,870 | 65,916,367 | Different behavior of boost::future and std::future | To be specific, boost::future doesn't seem to block in the destructor. And boost documentation didn't mention it. However std::future did mention it.
If I want to chain some .then() to boost::future I also need to chain a .get() call at the end to force the temporary object to block to get the correct behavior. Is that... | https://www.boost.org/doc/libs/1_75_0/doc/html/thread/synchronization.html
The returned futures behave as the ones returned from boost::async, the destructor of the future object returned from then will block. This could be subject to change in future versions.
(2015) https://www.boost.org/doc/libs/1_75_0/doc/html/th... |
65,908,261 | 65,908,566 | Is there a way to interleave static library and dependent dll compilation (MSVC)? | When compiling multiple libraries with MSVC, the compilation process can execute in parallel for each library.
On the other hand, If I have a dll that link together a handful of static libraries, the dll compilation process must wait until all libraries finish their compilation. At least with the workflow I'm currentl... | Unless you have edited the library's source code, MSVC doesn't compile it (again). But if you have edited it, then obviously you will have to one way or the other (well if you want the features to be in the build). If you edit just the dependent, unless your not talking about circular dependencies, the dependencies won... |
65,908,784 | 65,908,949 | C++ Int array type in function call | I have an array initialised like the following:
int example[5][5];
example[5][5] = 55;
And a function:
void example_function(auto inArray, int z){
cout << "example text = " << inArray[z][z] << endl;
}
And I am calling it into the function like this:
example_function(example, 5);
As you can see, I have the parame... | If the array passed to the function is known beforehand, in this case as int example[5][5];, you can use the following,
void example_function(int (&inArray)[5][5], int z){
cout << "example text = " << inArray[z][z] << endl;
}
Here we take the array by reference to avoid array decay.
If the size might vary at runti... |
65,910,307 | 65,910,448 | How to implement a "either nested type or void" trait? | I'm working with some classes that may have a nested type defined. Whenever this nested type is not defined I pretend like this nested type is void. For example, here is the code that should work:
struct HasNestedTypeDefined {
using Nested = int;
};
struct VoidNestedTypeDefined {
using Nested = void;
};
struc... | Note your last attempt
template<typename T, typename = void>
struct reveal_nested_type {
using type = void;
};
template<typename T>
struct reveal_nested_type<T, typename T::Nested> {
using type = typename T::Nested;
};
actually does work for reveal_nested_type<VoidNestedTypeDefined>. What's happening is that ... |
65,910,427 | 65,910,552 | Why does the second destruction of the temporary object on the code below occurs before the message "End of f" is printed? | The (code below)
#include<iostream>
struct C { C() { std::cout << "C()\n"; } ~C() { std::cout << "~C()\n"; } };
void f() {
C * pc = new C;
using C2 = C;
pc->C::~C2(); // OK, destroys *pc
C().C::~C(); // undefined behavior: temporary of type C destroyed twice
std::cout << "End of f\n";
}
int main(){
... | First of all, even if you copied this from the standard, it's still undefined behavior, so the answer could be just the compiler felt like it.
However, I understand your question is why End of f is printed after the second ~C() and not at the end of the scope (i.e. after the print).
The answer is that temporaries in an... |
65,910,460 | 65,915,604 | CMake Error: install EXPORT includes target which requires target that is not in any export set | I'm writing a library that has a few dependencies that are pulled in via CMake's FetchContent. In my toplevel CMakeLists.txt, close to the top I have:
include(external/dependencies.cmake) which contains
include(FetchContent)
# a pretty awesome text formatting library
option(_USE_FMT "include components for formatti... | Because in fmt, install rules are disabled if it's a subproject...
# Determine if fmt is built as a subproject (using add_subdirectory)
# or if it is the master project.
if (NOT DEFINED FMT_MASTER_PROJECT)
set(FMT_MASTER_PROJECT OFF)
if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)
set(FMT_MASTER_PROJECT... |
65,910,752 | 65,911,473 | Ambiguous fread()/fwrite() documentation | After RTFM, it is now somewhat unclear to me what I can really infer from the return value of fread()/fwrite() if the returned value is less than the number of requested elements.
Consider at first
nhave = fread(dst, 1, nwant, fp);
From the C17 standard (7.21.8.1/3):
The fread function returns the number of elements ... |
So, what's going on here? Just sloppy wording?
I think you are parsing words too finely, which you can characterize as sloppy wording of the specifications if you prefer.
Consider fread() first. C17 says,
The fread function returns the number of elements successfully read,
which may be less than nmemb if a read err... |
65,910,802 | 65,928,682 | Copying big endian float data directly into a vector<float> and byte swapping in place. Is it safe? | I'd like to be able to copy big endian float arrays directly from an unaligned network buffer into a std::vector<float> and perform the byte swapping back to host order "in place", without involving an intermediate std::vector<uint32_t>. Is this even safe? I'm worried that the big endian float data may accidentally be ... | After your edit:
Regarding the auto datum = reinterpret_cast<uint32_t*>(numbers.data());: This is not allowed in C++, one can only safely type-pun to uint8_t (only if CHAR_BIT == 8, more precisely this type-punning exception only holds for the char types)
Old answer:
Below is for the question before the edit (the one w... |
65,911,007 | 65,911,369 | Converting a priority queue to vector of ints in C++ | I am trying to convert a min-heap priority queue to return as a vector of ints. Is this type conversion is possible in C++;
| The C++ std::priority_queue uses a container for storage https://en.cppreference.com/w/cpp/container/priority_queue
By default it is class Container = std::vector<T>
Is this what you want to get access to ? If so, though luck:
C, the underlying container (protected member object)
It is not exposed. You could derive f... |
65,911,416 | 65,911,487 | class method not returning value | I have a method inside a class that is not returning a value.
These are the relevant variables that are being used in the method, they are in the private part of the class
int hieght_of_plane = 0 ;
int position_of_plane = 0 ;
bool landing_gear = true ;
bool is_flying = false ;
bool is_alive = true ;
And here is the me... | The case that falls through is when flying == true and hieght_of_plane is greater than 3.
if (is_flying == true)
{
if (hieght_of_plane <= 3)
{
The 2nd if statement does not have an else, which is necessary for returning a value.
Edit 1: An else clause
The else clause should be used for the "not... |
65,911,435 | 65,911,450 | C++" no match for operator<<" when printing a std::vector<std::pair> | I want to print the vector dicVec in order to check if everything is as I want. But I can´t. I already looked it up, but nothing helped.
This is my current code:
void Translate::read(){
int i = 0;
std::ifstream dic("ende.dic");
if (dic.is_open())
{
std::string dicLine;
while (std::getli... | You are trying to print out a std::pair, but there is no standard operator<< implemented for std::pair, so you will have to write you own.
Even if you fix that, your code will still fail, because dicVec is empty when you call std::cout << dicVec[i]; You are not adding dicPair to dicVec before printing the contents of ... |
65,911,537 | 65,911,591 | What does `uint` means in c++ while the declaration of a variable in class? | What does uint means in c++ while the declaration of a variable in class?
See here for the referance.
Is it part of a c++ library such as eigen/core?
Does that mean unassigned int?
I searched on google but could not find anything concrete.
| It means whatever the author decided it means!
uint is not part of C++, so it must come from one of the libraries used by that code. Some Googling tells us that it is indeed Eigen.
By convention, it's an unsigned integer type, probably one without a fixed width, so unsigned int.
|
65,911,610 | 65,911,699 | Concatenate two typed variadic template packs | Consider this struct
template<std::size_t... a>
struct A{};
How can I concatenate two typed variadic template arguments?
concat<A<1,2,3>, A<4,5,6,7>> // should be of type A<1,2,3,4,5,6,7>
| You can implement this with a specialization that handles instantiations of A.
template<typename...>
struct concat_impl; // just a declaration, to allow for specializations
template<std::size_t... s1, std::size_t... s2>
struct concat_impl<A<s1...>, A<s2...>> { // specialize
using type = A<s1..., s2...>... |
65,911,881 | 65,912,019 | printf tilde operator in c | I know that the ~ operator is NOT, so it inverts the bits in a binary number
unsigned int a = ~0, b = ~7;
printf("%d\n",a);
printf("%d\n",b);
printf("%u\n",a);
printf("%u\n",b);
I guessed 0 will be 1 and 7 (0111) will be 8 (1000) but the output was
-1
-8
4294967295
4294967288
how did ~0 and ~7 become -1, and -8? also... | The ~ operator simply inverts all bits in a number.
On most modern compilers, int is 32 bits in size, and a signed int uses 2's complement representation. Which means, among other things, that the high bit is reserved for the sign, and if that bit is 1 then the number is negative.
0 and 7 are int literals. Assuming t... |
65,912,189 | 65,912,598 | How to disable DYNAMICBASE in msbuild vcxproj | I would like to pass the linker option /DYNAMICBASE:no to the msvc linker via the vcxproj file which msbuild is using to compile the project.
If someone would like to replicate my failures I am using this vcxproj file to compile bitcoind using this command to build the project:
msbuild bitcoind/bitcoind.vcxproj /p:Plat... | To turn off /DYNAMICBASE in the .vcxproj file insert the following before the <ItemGroup> list.
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<RandomizedBaseAddress>false</RandomizedBaseAddress>
</Link>
</ItemDefinitionGroup>
To have it apply to all builds, in... |
65,912,325 | 65,919,408 | What does "optional prototyping in C whereas mandatory prototyping in C++" mean? | On page 249, "C++ Primer Plus by Stephen Prata" says
ANSI C borrowed prototyping from C++, but the two languages do have
some differences. The most important is that ANSI C, to preserve
compatibility with classic C, made prototyping optional, whereas C++
makes prototyping mandatory. For example, consider the following... | C’s original style of function declarations and definitions did not specify the types of the arguments in the argument list. For example:
/**
* Old style function declaration - the parameter list only
* specifies the argument names.
*/
int foo( x, y, z );
/**
* Old-style function definition - the parameter list
... |
65,912,645 | 65,912,929 | Is there any possible way to get origin value using transformed iterator? | C++20 introduces the views::elements, views::keys and views::values to easily deal with range of tuple-like values:
std::vector v{std::tuple{'A', 1}, {'B', 2}, {'C', 3}};
auto it = std::ranges::find(v | std::views::elements<0>, 'B');
assert(*it == 'B');
After applying the adaptor, v | std::views::elements<0> become a ... | It's possible to get an iterator to the underlying range by calling .base().
assert(*it.base() == std::tuple{'B', 2});
But it might be more idiomatic to use a projection with std::ranges::find.
std::vector v{std::tuple{'A', 1}, {'B', 2}, {'C', 3}};
auto it = std::ranges::find(v, 'B', [](auto& e) { return std::get<0>(e... |
65,913,008 | 65,914,520 | Deinterleave audio data in varied bitrates | I'm trying to write one function that can deinterleave 8/16/24/32 bit audio data, given that the audio data naturally arrives in an 8 bit buffer.
I have this working for 8 bit, and it works for 16/24/32, but only for the first channel (channel 0). I have tried so many + and * and other operators that I'm just guessing ... | You're actually pretty close. But the code is confusing: specifically the variable names and what actual values they represent. As a result, you appear to be just guessing the math. So let's go back to square one and determine what exactly it is we need to do, and the math will very easily fall out of it.
First, jus... |
65,913,091 | 65,913,325 | Is there a solution for this case? | This is a Windows Desktop Application project created by Visual Studio.
I have a Dialog resource created from the Resource View that has a Static Text.
I'm using this dialog in order to show errors to the user:
DialogBox(hInst, MAKEINTRESOURCE(IDD_MY_MESSAGE_BOX), hWnd, MyMessageBoxProc);
The reason I'm using a Dialog... | Just change the text in your window procedure (MyMessageBoxProc) by handling WM_INITDIALOG message. If you wish to supply the text to the dialog, then create it using DialogBoxParam instead, which is then accessible via the lParam parameter.
e.g.
INT_PTR MyMessageBoxProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM ... |
65,913,287 | 65,914,190 | How to use std::partial_sum and output to a std::map? | I want an output map that has { {0,1},{1,2},{2,3},{3,4},{4,5} }, c++11 only. Any ideas?
std::map<int, int> m, out;
for( auto i=0; i < 5; ++i )
m[i] = 1;
std::partial_sum( m.begin(), m.end(), std::inserter( out, out.begin() ),
[]( const std::pair<int,int>& a, const std::pair<int,int>& b )
{ ... | You can't. Not directly, at least. The issue is that std::map<int, int>::iterator::value_type is std::pair<const int, int>, and that const prevents an object of that type from being assigned to.
--
Take a look at this possible implementation for std::partial_sum:
template<class InputIt, class OutputIt, class BinaryOp... |
65,913,577 | 65,914,088 | why a 2-dimensional vector of auto_ptr in C++ does not work? | I am working on a 2-dimensional vector (vector of vector) to carry some pointers in C++.
std::vector< std::vector<object*> > data;
here object is a class and each entry of data carries a pointer to an object instance. I make it work in C++ but the memory management makes it hard to maintain when I apply it to other cod... | First, don't use std::auto_ptr. As you've found out, it cannot be used as an element of a vector, because it doesn't have an appropriate copy constructor. It has been deprecated since C++11 in favour of using std::unique_ptr instead. std::auto_ptr was removed from the language in C++17.
Second, objects pointed by &sour... |
65,914,452 | 65,914,721 | How can I find prime reversed numbers? | I have to write a program to check if the entered number has these qualifications:
A number that is prime it self, the reverse of that number is also prime, and the number's digits are prime numbers too (Like this number: 7523).
If the needs meet, it has to show "yes" when you enter and run the program otherwise "no".... | I have done some changes to your code, and added comments everywhere I've made changes. Check it out:
#include <iostream>
#include <conio.h>
using namespace std;
bool prime_check(int x) { // I have changed the datatype of this function to bool, because I want to store if all the digits are prime or not
int i, flag... |
65,914,838 | 65,914,937 | Trying to pass a function as an argument to a timer, unresolved linker error | I am just starting out c++, and am trying to pass a function that I want to be repeated to a timer that is supposed to trigger it. I am attempting to use templates to achieve this, but keep getting LNK2019 error stating that I have unresolved externals.
Main class:
#include <iostream>
#include <thread>
#include "Window... | The header .H file needs to implement all templated methods like this:
class TimerClass
{
private:
bool timerOn = false;
public:
double time = 0;
double interval;
TimerClass(double interval);
template<typename Function>
void startTimer(Function func)
{
startTimer(this->interval, f... |
65,914,930 | 65,916,006 | C++ array - how to display the names? | Suppose I have a number of participants of diving competition and being scored by judges.
I need to display the total scores according to name of the participants.
How do i solve this problem?
int scores[5][2], i, j;
int sum =0;
for(i=0;i<5;i++)
{
char name [50];
cout << "Enter participant's name: ";
cin >... | first of all its my first answer here (ever) so im very exited an hope it helps! =)
when you wrote "char name[50]", you actually made an array of chars (array of singal letters), and every cycle in the loop you wrote over that same array(and only the first letter of the a name each time).
I think you ment to create an ... |
65,914,999 | 65,915,119 | How to add a Average of the numbers in c++ text.stream | How to code Average of the numbers in case 5? I already done a convert string to int. How can I make average of the numbers from text file named "dane.txt"?
case 5: //srednia
{
fstream plik;
plik.open("dane.txt");
while(!plik.eof())
... | Add two variables to keep track of the count of numbers, and the total from adding up all the numbers (apologies for the English names).
Then at the end of the loop you can divide the total by the count and that is your average.
int total = 0;
int count = 0;
...
... |
65,915,174 | 65,916,648 | Get me to calculate displacement. I don't how what will be the formula according to this program | class Vehicle;
class Point {
private:
float x, y;
public:
Point(float x = 0,float y = 0){
this->x = x;
this->y = y;
}
void move_north(float num){
y = y + num;
}
void move_south(float num){
y = y - num;
}
void move_west(float num){
x = x - num;
... | The distance between two points no matter the dimension is called Euclidean_distance
so your method is
float calculate_displacement() const
{
return sqrt (delta_x*delta_x + delta_y*delta_y);
}
and
delta_x = starting_position.x - current_position.x
delta_y = starting_position.y - current_position.y
|
65,915,206 | 65,915,324 | Returned std::string by value - why does the internal buffer point to existing memory? | class StringPool
{
public:
explicit StringPool(size_t reserve = 0);
std::string Pool(const std::string& str);
private:
std::vector<std::string> m_pool;
};
StringPool::StringPool(size_t reserve)
{
if (reserve > 0)
m_pool.reserve(reserve);
}
std::string StringPool::Pool(const std::string& str)
... |
Why does the internal buffer of tmp have the same address of the returned element?
I assume that by returned "element", you mean the internal buffer of the returned string object.
It is unclear whether you refer to the internal address of tmp before the assignment or after the assignment. In practice, the address ty... |
65,915,344 | 65,915,794 | Allow template parameter of function pointer type to accept functions of any return type | Is there a way to allow a template parameter of function pointer type to accept a function of any (rather than a specific) return type, when the function's return value is not actually used? Here's an MCVE to illustrate what I mean:
int returnInt(int) { return 0; }
void returnVoid(int) { }
template <int (*Func)(int)>
... | You can declare the template parameter as auto (since C++17) to make it working with any function pointer types.
template <auto Func>
struct foo { void bar(int x) { Func(x); } };
LIVE
And if you want to check the type with SFINAE:
template <auto Func, std::enable_if_t<std::is_function_v<std::remove_pointer_t<decltype(... |
65,915,417 | 65,919,075 | Using WAVEFORMATEXTENSIBLE with WAVE_FORMAT_IEEE_FLOAT, waveOutOpen returns WAVERR_BADFORMAT | I have been using WAVEFORMATEX with WaveOut to play audio in Windows, in stereo at rates from 44.1KHz to 192KHz using WAVE_FORMAT_IEEE_FLOAT. The program is written in C++ and compiled in MinGW. This is all working correctly:
https://github.com/Raptor007/AutoDJ/blob/60f4debca2103e669a5d1b822b04c73cdcdaf05b/AutoDJ.cpp... | If are using a WAVEFORMATEXTENSIBLE structure, you have to indicate that by setting the correct format tag in the "base" WAVEFORMATEX.
wfx.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
See the documentation of the Format member of WAVEFORMATEXTENSIBLE.
This makes it possible for the called code (that only has a pointer ... |
65,915,671 | 65,931,994 | Adding two string arguments in Node Addons | I am trying to add two string arguments in my addon but I could not get it to work. I always get an error about the types of the two arguments.
My function:
void Add(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
Local<Context> context = isolate->GetCurrentContext();
// Check th... | Found the solution. The only problem was that I should have converted the Local<String> type to std::string. And after adding them together, convert them back to Local<String> when returning the value.
Code:
void Add(const FunctionCallbackInfo<Value> &args) {
Isolate *isolate = args.GetIsolate();
Local<Context> co... |
65,915,922 | 65,931,527 | Class inheritance but encounter redefinition error in C++ | I'm learning C++ Data Structure, about implementing Stack using Array and Linked List. The array is default in C++ but I've constructed a Linked List class. The code below is my Linked List header file
#pragma once
#include "Node.h"
#include "Stack.h"
class LinkedList
{
public:
LinkedList() {head = NULL;}
Node*... | Hi as @Some_programmer_dude said
Classes can't be "overloaded", they must have different names if they are defined in the same namespace.
I would use polymorphism for this situation.
So we define a base class named Stack, then will create two other classes named LinkedListStack and ArrayStack which both derive form S... |
65,916,289 | 65,916,419 | Template parameters of function type with auto return type arguments of previous template parameter types | I have a template with two parameters: the first is a type, and the second is a function pointer with an argument whose type is the first template parameter. This MCVE works:
void returnsVoid(int x) { }
template <typename T, void (*Func)(T)>
struct foo { void bar(T t) { Func(t); } };
int main(int, char *[]) {
foo... | This is gcc's bug. (Bug 83417)
It seems gcc failing deducing the type of auto when using the 1st template parameter T as function parameter; you can use std::type_identity (since C++20) to exclude it from participating in template argument deduction.
// workaround for gcc
template <typename T, auto (*Func)(std::type_id... |
65,916,601 | 65,916,878 | Clone derived class from base class pointer | In our legacy project we have a function that takes reference to a base class and creates a copy of the derived class on the heap. This is solved essentially like this: https://godbolt.org/z/9ooM4x
#include <iostream>
class Base
{
public:
virtual Base* vclone() const = 0;
int a{7};
};
class Derived : public B... | I also think you probably cannot improve the code in the sense to make it shorter.
I would say this implementation is basically the way to go.
What you could do is to change the return value of Derived::clone to Derived *. Yes C++ allows this.
Then a direct use of Derived::clone yields the correct pointer type and Base... |
65,917,688 | 65,917,795 | How to make several parameters in a template for a call without overloads? | How to make one template so that it can be called with several parameters, without creating unnecessary overloads with code repetition
I have a template something like this
struct demo {
template <class T1, class T2, class T3>
demo(T1&& tipe_1, T2&& tipe_2, T3&& tipe_3) {
// code that is too lazy to repeat
st... | You should be able to use C++17 fold expressions for this:
template <typename... Ts>
void createFullPath(Ts&&... components)
{
std::filesystem::create_directories((std::filesystem::path{components} / ...));
}
Live demo here.
Note this requires all Ts to have a proper operator/ functionality, which would make them st... |
65,918,298 | 65,920,835 | How to export an x64 only package in vcpkg? | I have create a prebuilt package using vcpkg create command and then installed it on my system. I then tried to export this package so I can use it on other systems using the following command :
vcpkg export my-lib-static --zip
but this complains about the fact that the x86 version is not installed and I need to insta... | As it turns out, the command that I wrote was wrong.
Since I have previously installed my lib like :
vcpkg install my-lib-static:x64-windows
I had to export it in the same manner that is :
vcpkg export my-lib-static:x64-windows --zip
Not specifying the architecture and platform, means using x86-windows and hence th... |
65,918,405 | 65,919,947 | Is mixing modules and headers in C++20 possible / acceptable? | I'm actually trying to understand the C++20 modules system by writing my own little module. Let's say I want to provide a function that deletes all the spaces at the beginning and the end of a string (a trim function). The following code works without problem.
module;
export module String;
import std.core;
export st... | Yes, modules can be used together with header files. we can both import and include headers in the same file, this is an example:
import <iostream>
#include <vector>
int main()
{
std::vector<int> v{1,6,8,7};
for (auto i:v)
std::cout<<i;
return 0;
}
When you create modules, you're free to export entities in t... |
65,918,770 | 65,930,474 | How to "deep freeze" object like in JavaScript? | As we know, in JavaScript, we can freeze an object in runtime such that it will be immutable, furthermore, we can recursively freeze its mutable members such that it can no longer be modified from now on. Is it possible to achieve similar thing in C++?
I am aware of that this will inevitably cause an overhead and I am ... | The solution is to use const.
Say you have a class MusicalSheet. You can define getters and setters for whatever data you want. Make the setters const so you can't call them on a const object or reference.
class MusicalSheet
{
public:
void setNote(size_t position, Note note);
const Note& getNote(size_t position... |
65,919,217 | 65,919,273 | Debugging a simple function | So our professor gave us the task to debug this code. We can use the compiler and also try to use the gdb debugger.
#include <cstdlib>
#include <iostream>
#include <vector>
std::vector<int> reversed(const std::vector<int>& v) {
std::vector<int> result;
for (std::size_t i = v.size() - 1; i >= 0; --i) result.push_ba... |
terminate called after throwing an instance of 'std::invalid_argument'
what(): stoi
The function that throws an exception is std::stoi that is used to interpret a signed integer value in a string.
In this loop:
for (std::size_t i = 0; i < argc; ++i) {
// atoi converts a string to a number
int number = std:... |
65,919,771 | 65,924,210 | Why does this LRESULT CALLBACK-function not work after adding code to let it react to a button press? | So this is the function that works:
LRESULT CALLBACK windowCallback(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
LRESULT result = 0;
//check and execute input
switch (uMsg) {
case WM_CLOSE:
case WM_DESTROY: {
running = false;
} break;... | Your WM_SIZE handler is missing a break statement:
case WM_SIZE: {
...
break; // <-- ADD THIS
}
Without that, any WM_SIZE message that is received will fall through to your WM_KEYDOWN handler, skipping DefWindowProc().
|
65,919,790 | 65,921,688 | C++ Why base class/struct constructor can't have more than one argument to be implicitly callable from derived? | Why this can't work:
struct Base {
Base(int a, int b) {}
};
struct Derived: Base {
// using Base::Base; // unless I add this
};
int main() {
Derived d(0, 0);
}
While this can:
struct Base {
Base(int a) {}
};
struct Derived: Base {
// using Base::Base; // without this line
};
int main() {
... | The "magic" is that you're accidentally using aggregate initialization. In C++20 (and not before), you can invoke aggregate initialization by using parenthesis instead of curly braces, so long as no actual constructor (like the copy/move constructor) would have been invoked. This was done to allow indirect construction... |
65,920,024 | 65,929,052 | ConnectNamedPipe() function triggers "Debug Error! abort()" when called from within a method of a Functor that's passed as an argument to a new Thread | Error
Executing the below in Visual Studio triggers "Debug Error! abort() has been called":
if(m_handle==INVALID_HANDLE_VALUE) return(false); // no return here, therefore m_handle is valid (?)
if(!m_connected){ // some bool indicating a connection doesn't already exist
if(ConnectNamedPipe(m_handle,NULL)==0){ // --... | PipeFunctor pipeF(); is a function declaration (a function named pipeF taking no arguments and returning a PipeFunctor). It is not a variable declaration, like you probably intended. PipeFunctor pipeF; is a variable declaration, as is PipeFunctor pipeF{};.
In any case, when using std::thread, you are passing it a refer... |
65,920,107 | 65,920,257 | C++ Convert 4 Hex Values to Float | I am trying to convert 4 hexadecimal values to a float.
The hex values are for example 3F A0 00 00. In binary representation they would correspond to 00111111 10100000 00000000 00000000. If these 4 binary values are interpreted as one 32-bit float (accordingly to IEEE754) the decimal value of the float should be 1,25.
... | #include <iostream>
#include <cstring>
using namespace std;
int main()
{
unsigned char bytes[] = {0x3F, 0xA0, 0x00, 0x00};
uint32_t x = bytes[0];
for (int i = 1; i < std::size(bytes); ++i) x = (x << 8) | bytes[i];
static_assert(sizeof(float) == sizeof(uint32_t), "Float and uint32_t size dont matc... |
65,920,457 | 65,976,260 | CAN BUS STM32 Nucleo F429ZI CAN Write Fail | It is Veysel My board is STM32 Nucleo F429ZI and I use Mbed-os 6.6.0. I can read from my car CANBus data but I am not able to write on the bus. I tried it with two STM32 (same boards) and my trancivers are SN65HVD230
So I know that I can read on the CANBus , but I cannot write.
I have tried , https://os.mbed.com/users... | for me it sounds like you forgot to drive the "RS"-pin of the CAN Transciever. This is a bit misleading in the datasheet, but it is not only "slope" control, but it also sets the Transciever to sleep. I'd recommend to use a 10k slope control resistor unlesss needed otherwise as shown here: Schematics
|
65,920,655 | 65,922,248 | How to set a multivalued property with SetProps | Can anyone provide a simple sample of how to create a multivalued string property(PT_MV_STRING8) and then set it with SetProps? I cannot find any in MSDN.
| See MultiValuePropertyEditor.cpp in MFCMAPI: https://github.com/stephenegriffin/mfcmapi/blob/master/UI/Dialogs/Editors/MultiValuePropertyEditor.cpp
|
65,920,683 | 65,920,758 | What is the LibTorch equivalent to PyTorch's torch.no_grad? | When testing a network in PyTorch one can use with torch.no_grad():. What is the Libtorch (C++) equivalent?
Thanks!
| The equivalent in LibTorch is torch::NoGradGuard no_grad, see documentation.
|
65,920,834 | 65,921,027 | no template named 'tuple' in C++ | I am not allowed to initialise a tuple in C++. When I compile it comes up the following error while pointen at tuple: no template named 'tuple'. I am using Mac and have specified my tasks.json as shown in the bottom of the page.
Code
#include <tuple>
#include <iostream>
using namespace std;
int main() {
tuple<int,... | Based on the comments, the problem was, that the task cppbuild was used instead of shell, and for that task, no c++ version was defined. Due to that default version for that compiler was used which does not support tuple.
Adding "-std=c++17", to the args of cppbuild solves that problem.
|
65,921,565 | 65,921,642 | C++ and incomplete friend classes | I looked around to find the rationale behind the choice made in C++ compiler about what I've called imaginary friends. Unfortunately I didn't find any explanation so I'm asking experts.
I wondering why C++ does not complain about the following code. Classes and method indicate as friends do not exist actually but if yo... |
I wondering why C++ does not complain about the following code.
C++ is a programming language specification.
You could read some C++ standard like n3337 (or a newer one). That specification does not mention "complaints".
GCC is a compiler implementing more or less C++. You could add your own GCC plugin emitting the d... |
65,922,386 | 65,922,725 | How to add member function of template class only on specific types using type_traits | C++ | template <typename T>
class A
{
template <std::enable_if_t<std::is_signed_v<T>, bool> = true>
constexpr value_type determinant()
{
}
}
I wanna determinant function is instantiated only when type T is signed type
so I try this codes, but when type T is unsigned compiler stil... | With SFINAE you can enable/disable a method of a class when the condition tested is related to a template parameter of the method itself. Doesn't works testing a template parameter of the class.
You can solve the problem passing through a method template parameter that is defaulted with the type of the class/struct tem... |
65,922,475 | 65,922,898 | mark function as non-candidate for const | I have a function that doesn't alter anything. The function pointer part of an array of similar function pointers and can't be marked as const as it will not be able to be part of that array then.
I have a compiler flag active that warns me if a function is a potential candidate for being declared const. And that is ca... | You can temporarily disable warnings in gcc and clang with a pragma:
class C
{
// First save state of warnings
#pragma GCC diagnostic push
// Then ignore warning for this function
#pragma GCC diagnostic ignored "-Wsuggest-attribute=const"
void f3(){}
// Lastly restore warning state
#pragma GCC diagnostic pop
};
Thi... |
65,922,595 | 65,923,887 | SetWindowsHookEx hooking into every running program | I have written a small DLL that is being injected into a game to apply runtime fixes. I've decided to add some Keyboard Listeners:
while (1)
if (AsyncKeyState(...)) (...)
However, this is taking up CPU usage, and introducing some noticeable stuttering. So I decided to use a callback methodology as suggested by MSD... | You ARE hooking every application process, because you are installing the hook globally, by setting the dwThreadId parameter of SetWindowsHookEx() to 0:
dwThreadId
Type: DWORD
The identifier of the thread with which the hook procedure is to be associated. For desktop apps, if this parameter is zero, the hook procedure... |
65,922,844 | 65,923,234 | C++ mutex doesn't work - synchronization fails | I would like to apply as simple mutex as possible.
#include <iostream>
#include <thread>
#include <vector>
#include <functional>
#include <algorithm>
#include <mutex>
using namespace std;
int sum;
static mutex m;
void addValue(int value)
{
m.lock();
sum += value;
m.unlock();
}
int main()
{
int count... |
C++ mutex doesn't work - synchronization fails
Why does everyone learning this stuff for the first time assume the tried-and-tested synchronization primitives that work for everyone else are broken, and not their assumptions?
The mutex is fine. Your mental model is broken. This should be your starting assumption.
I ... |
65,922,852 | 65,923,099 | Find common element using recursive and return as vector | I am trying to find common elements of two arrays but I am getting false results.
Where is my mistake? It seems like everything is normal.
template<class T>
bool contains(T arr,int size, int num){
for(int i=0; i<size;++i)
if(arr[i] == num)
return true;
return false;
}
I am trying to use tai... | Your 'recursion end' condition is "off-by-one" – it should be if (s1 > 1) instead of if (s1 > 0).
As it stands, you end up calling cElemet with a value of 0 (froms1 - 1) and then, in that recursion, you attempt to access ar1[s1 - 1] when s1 is zero, which causes undefined behaviour.
Changing your function to the follow... |
65,923,238 | 65,925,105 | How to deal with pragma once? | To my understanding Visual Studio C++ projects use #pragma once in the very top of header files to prevent multiple inclusion.
And the same is achieved, in Qt Creator projects, with
#ifndef FILE_H
#define FILE_H
// Code here
#endif
Let's say I got a Visual Studio project and I want to play with Qt Creator. How to ... | Yes, really, #pragma once originates from Microsoft C++, but nowadays it is supported by at least two another most used modern C++ compilers (i.e GCC and clang). So you should not have a problems with it.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.