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 |
|---|---|---|---|---|
70,486,437 | 70,486,469 | Equivalent in C++ of an array with unidentified length | Let us consider this line of code in C# :
int[] int_array;
What is its equivalent in C++?
Is it : int* int_array ?
| The equivalent in c++ is
std::vector<int> int_array;
|
70,486,532 | 70,487,027 | Unable to have 100 factorial with C++ on output screen(displaying 0) | Well I am stuck on this problem for quite a while:
Question:
You are asked to calculate factorials of some small positive integers.
Input:
An integer t, 1<=t<=100, denoting the number of testcases, followed by t lines, each containing a single integer n, 1<=n<=100.
Output:
For each integer n given at input, display a line with the value of n!
//coded in c++
#include <bits/stdc++.h> //loadind up all the libraries at once.
using namespace std;
int main()
{ int T;
scanf("%d", &T);
//I am not doing "cin<<" cause "scanf" is faster than it
for (int i = 0; i < T; i++)
{
int N;
scanf("%d",&N);
long long int product = 1;
while (N >0){
product = product * N;
N--;
}
printf("%lld\n",product);
}
return 0;
}
I am able to get 10!,20! but unable to get 100! (factorial)
so the extreme case doesn't satisfy. Please help me to get a good data type for my variable as 100! a factorial has over than 100 digits. It is displaying 0 when I input 100 on the terminal.
P.S - This problem is from CodeChef website (FCTRL2).
| A 64bit integer will overflow with 23!
Therefore you need to do it with digits and a vector.
This is a rather simple task. We can do it like we would do it on a piece of paper. We use a std::vector of digits to hold the number. Because the result will be already too big for an unsigned long long for 23!.
The answer will be exact.
With such an approach the calculation is simple. I do not even know what to explain further.
Please see the code:
#include <iostream>
#include <vector>
int main()
{
std::cout << "Calculate n! Enter n (max 10000): ";
if (unsigned int input{}; (std::cin >> input) && (input <= 10000)) {
// Here we store the resulting number as single digits
std::vector<unsigned int> result(3000, 0); // Magic number. Is big enough for 100000!
result.back() = 1; // Start calculation with 1 (from right to left)
// Multiply up to the given input value
for (unsigned int count = 2; count <= input; count++)
{
unsigned int sum{}, remainder{};
unsigned int i = result.size() - 1; // Calculate from right to left
while (i > 0)
{
// Simple multiplication like on a piece of paper
sum = result[i] * count + remainder;
result[i--] = sum % 10;
remainder = sum / 10;
}
}
// Show output. Supporess leading zeroes
bool showZeros{ false };
for (const unsigned int i : result) {
if ((i != 0) || showZeros) {
std::cout << i;
showZeros = true;
}
}
}
else std::cerr << "\nError: Wrong input.";
}
Using a bigint library will be much faster.
Developed and tested with Microsoft Visual Studio Community 2019, Version 16.8.2.
Additionally compiled and tested with clang11.0 and gcc10.2
Language: C++17
|
70,486,544 | 70,486,602 | CRT Detected that the application wrote to memory after end of heap in C++ | I have created a class of MyString. My code was working just fine but when I wrote the destructor for my class it is giving me the error at delete keyword. Please help me out where is the problem and what is the solution.
MyString Header File
#pragma once
#ifndef MYSTRING_H
#define MYSTRING_H
class MyString
{
private:
char* str;
int length;
public:
MyString();
MyString(const char*);
~MyString();
};
#endif
MyString CPP File
#include "MyString.h"
#include <iostream>
using namespace std;
MyString::MyString() {
length = 0;
str = new char[length];
str[length] = '\0';
}
MyString::MyString(const char* cString) {
length=strlen(cString);
str = new char[length];
for (int i = 0; i < length; i++)
str[i] = cString[i];
str[length] = '\0';
}
MyString::~MyString() {
delete[] str;
str = nullptr;
length = 0;
}
Main CPP File
#include "MyString.h"
#include <iostream>
using namespace std;
int main() {
//MyString s1;
MyString s2("OOP is Fun!!");
char name[15] = "Pakistan";
MyString s3(name);
return 0;
}
| length = 0;
str = new char[length];
The Golden Rule Of Computer Programming states: "your computer always does exactly what you tell it to do instead of what you want it to do". Here, this is exactly what you told your computer: allocate an array with 0 bytes. In other words, an empty array that does not contain anything at all. In other words: absolutely nothing was allocated.
str[length] = '\0';
This sets the first byte in the array to 0. Since nothing was allocated, this is undefined behavior, and your memory corruption, right here. You should've allocated 1 byte instead of 0 bytes.
The other constructor has the same defect. Since '\0' is a plain char, no different than any other char, like 'A', or '0', your code must always allocate an extra character for it, in addition to all other characters in the actual text string.
|
70,486,582 | 70,486,680 | Overrided method calling from base class c++ | I have 2 classes as NumberArray and PrimeNumberArray. PrimeNumberArray is subclass of NumberArray These classes have generate methods which generate array with random numbers. And I call these methods in NumberArray class. In main method I create PrimeNumberArray object and call the method "generateAndPrint" which should call PrimeNumberClass's generate method but actually the method is working from base class. Generate method which finds prime numbers is working. I just want to learn how to call it in method from base class.
Base class;
class NumberArray{
protected:
int* numbers;
int amount;
public:
NumberArray(int size = 0){
amount = size;
int array[amount];
numbers = array;
}
~NumberArray(){
delete[] numbers;
}
void generateAndPrint(){
generate();
print();
}
private:
void generate(){
int i = 0;
while (i < amount)
{
cout << "a" << endl;
int rnd = (rand() % 1000) +1;
numbers[i] = rnd;
i++;
}
}
void print(){
int i;
for (i = 0; i < amount; i++)
{
cout << numbers[i] << " -> ";
}
cout << endl;
}
};
Subclass;
class PrimeNumberArray: public NumberArray{
public:
PrimeNumberArray(int size){
amount = size;
int array[amount];
numbers = array;
}
void virtual generate(){
int i = 0;
while (i <amount)
{
int rnd = (rand() % 1000) +1;
int j;
int isPrime = 1;
for(j = 2; j < rnd / 2; j++){
if(rnd % j == 0){
isPrime = 0;
}
}
if(isPrime == 1){
numbers[i] = rnd;
i++;
}
}
}
};
Test class;
int main(){
PrimeNumberArray prime(5);
prime.generateAndPrint();
}
I tried to make generate method virtual but not works for me.
| The code below should get you started:
Make generate virtual void generate() in base class, and virtual void generate() override in derived class.
Create heap instances of PrimeNumberArray but assign them to NumberArray pointers; you can use smart pointers for this so you don't need to manually free the instances.
Then, you can just call whatever virtual methods using the pointer to the base class; the runtime polymorphism will kick in and end up calling the derived class methods.
You can do the numbers' management in the base class only; you don't need to duplicate the code in the derived class; just call the base class constructor from the derived class constructor with NumberArray(size).
Add a virtual destructor in the base class as well.
[Demo]
#include <iostream> // cout
#include <memory> // make_unique, unique_ptr
class NumberArray {
protected:
int* numbers;
int amount;
public:
NumberArray(int size = 0) : amount{size}, numbers{ new int[](size) } {}
virtual ~NumberArray() { delete[] numbers; }
void generateAndPrint() {
generate();
print();
}
private:
virtual void generate() {
for (int i = 0; i < amount; i++) {
std::cout << "a\n";
int rnd = (rand() % 1000) + 1;
numbers[i] = rnd;
i++;
}
}
void print() {
for (int i = 0; i < amount; i++) {
std::cout << numbers[i] << " -> ";
}
std::cout << "\n";
}
};
class PrimeNumberArray: public NumberArray {
public:
PrimeNumberArray(int size) : NumberArray(size) {}
virtual void generate() override {
for (int i = 0; i < amount; ) {
int rnd = (rand() % 1000) + 1;
bool isPrime = true;
for (int j = 2; j < rnd / 2; j++) {
if (rnd % j == 0) {
isPrime = false;
}
}
if (isPrime) {
numbers[i] = rnd;
i++;
}
}
}
};
int main() {
std::unique_ptr<NumberArray> prime{std::make_unique<PrimeNumberArray>(5)};
prime->generateAndPrint();
}
|
70,486,719 | 70,486,747 | How to call the function that accepts std::istream& | I am a beginner in C++. What is the correct way to call a function that expects std::istream&?
Tried it with read(std::cin);, but I get an error from the compiler.
typedef double Element;
template<typename T>
std::list<T> read(std::istream& i) {
Element input;
std::list<Element> l;
while(i>>input) {
l.push_back(input);
}
return l;
}
| This is not related to the std::istream& parameter.
The issue is that the function is a function template that requires an explicit template argument determining the type that is supposed to be read from the stream, e.g.:
read<int>(std::cin)
The error message from the compiler should be telling you something like that as well.
That aside, you are then not using T in the function. Probably you wanted to replace all uses of Element by T and remove the typedef.
|
70,486,930 | 70,487,270 | passing a lambda to a constructor while capturing variables | I have a compile-time error if I pass a lambda while capturing a variable.
Solutions out there are bound and tied to a specific class but essentially it's a use case with 1 to many class types (Observees). It's a kind of polymorphism.
Edit Richard in the comments pointed out the reason but I wonder if there's a workaround to achieve this, I ran into a blocker with free function pointers (see linked question), any lateral thinking?
Observee1
class Test {
int _value;
public:
void testMethod(int value) {
_value = value + 1;
}
};
Observee2 - A different class but same signature
class AnotherTest {
int _value;
public:
void anotherMethod(int value) { // same parameters, different implementation
_value = value * 2;
}
};
Observer
class Observer {
protected:
void (*_notify)(int value); // method called at runtime
public:
explicit Observer(void (*notify)(int value));
};
Attempted solution
auto *test = new Test();
auto *anotherTest = new AnotherTest();
auto *observer = new Observer([](int value) { // works
});
auto *observer2 = new Observer([test](int value) { // capturing test throws an error.
// requirement is to use captured object here.
test->testMethod(4);
});
auto *anotherObserver = new Observer([anotherTest](int value) {
anotherTest->testMethod(5);
});
Error
| The first comment fundamentally answers your question:
A capturing lambda is not convertible to a function pointer unless the capture list is empty.
By using a std::function<void(int)> instead of a function pointer, this limitation is resolved.
#include <functional>
class Test {};
class AnotherTest {};
class Observer {
protected:
std::function<void(int)> _notify;
public:
explicit Observer(std::function<void(int)> notify): _notify(notify) {}
};
int main() {
auto *test = new Test();
auto *anotherTest = new AnotherTest();
auto *observer = new Observer([](int value) {});
auto *observer2 = new Observer([test](int value) {});
auto *obserer3 = new Observer([anotherTest](int value) {});
}
|
70,487,013 | 70,487,093 | How is this object's destructor being called two times? | Can someone please explain how test1 is getting destroyed 2 times? Compiled with Visual Studio C++17
class test {
public:
test(int val):val_(val) {
cout << "test" << val_ << "constructor called\n";
}
~test() {
cout << "test" << val_ << " destructor called\n";
}
int val_;
};
int main() {
auto t2 = test(2);
{
auto t1 = test(1);
swap(t1, t2);
}
return 0;
}
Output:
test2constructor called
test1constructor called
test1 destructor called
test2 destructor called
test1 destructor called
| The general implementation of swap is as follows:
template<typename T>
void swap(T& x, T& y) {
T tmp = std::move(x);
x = std::move(y);
y = std::move(tmp);
}
There is a temporary variable tmp, which is destroyed when it leaves the scope of swap.
Since it is initialized by x at the beginning, its value is 1, and when it is assigned to y again, std::move will not change its value, so its value is still 1.
|
70,487,105 | 70,487,133 | Deleting dynamic elements in a vector | I have a program that has a vector. The vector takes pointers to an object which I dynamically create in my program. I then wish to delete these dynamic objects from the vector. For example:
int main()
{
vector<Account*> allAccounts;
auto timeDone = chrono::system_clock::now();
time_t transactionTime = chrono::system_clock::to_time_t(timeDone);
Account* a1 = new Savings(0, "Savings");
Account* a2 = new Current(0, "Current");
allAccounts.push_back(a1);
allAccounts.push_back(a2);
Transaction* initialTransaction = new Transaction("Initial Deposit", transactionTime, balanceAnswer);
allAccounts[0]->addTransaction(initialTransaction);
allAccounts[1]->addTransaction(initialTransaction);
for (int i = 0; i < allAccounts.size(); i++)
{
delete allAccounts[i]; //deletes all dynamically created accounts
}
}
I believed this was fine to do, however I'm starting to wonder if this does correctly delete the pointers in the vector. However I used a cout << allAccounts.size() after the delete and it still gives the size as 2 as if the account pointers were still in the vector.
Is this meant to happen?
Another note is that the Account object also has a vector of dynamic pointers that get passed from main in a function (allAccounts[i]->addObject(object)) and then these objects get deleted in a destructor in the same way. Is this also a valid thing to do?
Just so I get my worries out the way, this is what I do in account:
float balance;
string accountType
private vector <Transaction*> history;
Account::Account(float b, string a)
{
balance = b;
accountType = a;
}
void Account::addTransaction(Transaction* t)
{
history.push_back(t);
}
Account::~Account()
{
for (int i = 0; i < history.size(); i++)
{
delete history[i];
}
history.clear();
}
| What you are doing is fine (assuming Account has a virtual destructor) and there is no memory leak. The size of the vector is not affected by deleting the pointers you store in it.
The destructor needs to be virtual to not cause your program to have undefined behavior.
I would recommend storing a smart pointer like std::unique_ptr<Account> in the vector instead though. That would make the destruction of the stored objects automatic when the vector.is destroyed.
|
70,487,499 | 70,487,716 | Need help, How to convert bool type data in C++ WriteFile()? | I'm having trouble rewriting files, I'm getting this error. maybe someone can tell me how to convert the datatype so that the file can be rewritten
.\wInaPi.cpp: In function 'INT main(INT, CHAR**)':
.\wInaPi.cpp:30:54: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
30 | PIMAGE_DOS_HEADER image_dos_header = (PIMAGE_DOS_HEADER) file_read;
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.\wInaPi.cpp:76:63: error: invalid conversion from 'BOOL' {aka 'int'} to 'LPCVOID' {aka 'const void*'} [-fpermissive]
76 | WriteFile(PEFile, file_read, file_size, &returned_bytes, NULL);
| ^~~~~~~~~
| |
| BOOL {aka int}
In file included from C:/mingw64/x86_64-w64-mingw32/include/winbase.h:18,
from C:/mingw64/x86_64-w64-mingw32/include/windows.h:70,
from .\wInaPi.cpp:1:
C:/mingw64/x86_64-w64-mingw32/include/fileapi.h:186:62: note: initializing argument 2 of 'WINBOOL WriteFile(HANDLE, LPCVOID, DWORD, LPDWORD, LPOVERLAPPED)'
186 | WINBASEAPI WINBOOL WINAPI WriteFile (HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped);
|
part of my code
HANDLE PEfile = CreateFileA(target_process, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (PEfile != INVALID_HANDLE_VALUE)
{
DWORD file_size = GetFileSize(x_file, NULL);
PBYTE file_buffer = PBYTE(LocalAlloc(LPTR, file_size));
DWORD returned_bytes;
BOOL file_read = ReadFile(x_file, file_buffer, file_size, &returned_bytes, NULL);
if (file_read == TRUE && returned_bytes == file_size)
{
if (SetFilePointer(PEfile, 0, NULL, FILE_BEGIN) != INVALID_SET_FILE_POINTER)
{
WriteFile(PEfile, file_read, file_size, &returned_bytes, NULL); // got error here
}
}
}
| I do not know what file_read is, but the compiler tells you that:
you should not try to cast it to PIMAGE_DOS_HEADER;
WriteFile needs a pointer as a second parameter: WriteFile( PEFile, &file_read,....
[Edit - new information added to the question]
file_read is the result of ReadFile which is a BOOL (success or failure). Most likely you do not want to write this, anyhow: the third parameter must be the size of the data you are trying to write:
WriteFile(PEfile, &file_read, sizeof(file_read), &returned_bytes, NULL);
This will fix your compiling problem but it won’t fix the logic. And we cannot help you since it is not clear what you are trying to do. Maybe
WriteFile(PEfile, file_buffer, file_size, &returned_bytes, NULL);?
|
70,487,643 | 70,487,797 | Friend Function cannot access private members in C++ | I have created class and trying to overload ostream operator using a friend function but my friend is not able access private members of functions. Please help me figure out the problem. I have created another friend function named doSomething() from here I can call private member but not from overloaded function. Please help me updating overloaded stream insertion function.
Class Header File:
#pragma once
#ifndef MYSTRING_H
#define MYSTRING_H
class MyString
{
char* str;
int length;
public:
MyString();
MyString(const char*);
~MyString();
MyString (const MyString &Obj);
void Display() const;
int GetLength() const;
const MyString& operator = (const MyString&);
friend ostream& operator << (ostream &output,MyString&s);
friend void doSomething();
};
#endif
Class CPP File:
#define _CRT_SECURE_NO_WARNINGS
#include "MyString.h"
#include <iostream>
using namespace std;
MyString::MyString() {
length = 0;
str = new char[1];
str[length] = '\0';
}
MyString::MyString(const char* cString) {
length=strlen(cString);
str = new char[length+1];
strcpy(str,cString);
str[length] = '\0';
}
MyString::~MyString() {
delete[] str;
str = nullptr;
length = 0;
}
MyString::MyString(const MyString& Obj) {
length = Obj.length;
str = new char[length+1];
strcpy(str, Obj.str);
str[length] = '\0';
}
void MyString::Display() const {
cout << str << endl;
}
int MyString::GetLength() const {
return length;
}
const MyString& MyString::operator = (const MyString& Obj) {
this->~MyString();
length = Obj.length;
str = new char[length + 1];
strcpy(str, Obj.str);
return *this;
}
Main CPP:
#define _CRT_SECURE_NO_WARNINGS
#include "MyString.h"
#include <iostream>
using namespace std;
ostream &operator << (ostream& output, MyString s) {
output << s.length;
return output;
}
void doSomething() {
MyString s;
s.length;
}
int main() {
return 0;
}
| There are 2 problems with your code.
Mistake 1: You have not included iostream in MyString.h
Solution to mistake 1
MyString.h
#pragma once
#ifndef MYSTRING_H
#define MYSTRING_H
#include <iostream> //ADDED THIS
class MyString
{
char* str;
int length;
public:
MyString();
MyString(const char*);
~MyString();
MyString (const MyString &Obj);
void Display() const;
int GetLength() const;
const MyString& operator = (const MyString&);
friend std::ostream& operator << (std::ostream &output,MyString&s); //ADDED STD:: here
friend void doSomething();
};
#endif
Mistake 2: You have a missing & symbol while defining operator<< in main.cpp.
Solution to Mistake 2
main.cpp
#define _CRT_SECURE_NO_WARNINGS
#include "MyString.h"
#include <iostream>
using namespace std;
ostream &operator << (ostream& output, MyString &s) {//ADDED & HERE
output << s.length;
return output;
}
void doSomething() {
MyString s;
s.length;
}
int main() {
return 0;
}
Additionally, i have added #inlcude <cstring> in MyString.cpp. So MyString.cpp now looks like:
MyString.cpp
#define _CRT_SECURE_NO_WARNINGS
#include "MyString.h"
#include <iostream>
#include <cstring>
using namespace std;
MyString::MyString() {
length = 0;
str = new char[1];
str[length] = '\0';
}
MyString::MyString(const char* cString) {
length=strlen(cString);
str = new char[length+1];
strcpy(str,cString);
str[length] = '\0';
}
MyString::~MyString() {
delete[] str;
str = nullptr;
length = 0;
}
MyString::MyString(const MyString& Obj) {
length = Obj.length;
str = new char[length+1];
strcpy(str, Obj.str);
str[length] = '\0';
}
void MyString::Display() const {
cout << str << endl;
}
int MyString::GetLength() const {
return length;
}
const MyString& MyString::operator = (const MyString& Obj) {
this->~MyString();
length = Obj.length;
str = new char[length + 1];
strcpy(str, Obj.str);
return *this;
}
The program now works(compiles) as can be verified here.
Additional Problem
You should not call the destructor(the way you're calling on the current object) from inside operator='s body.
You can solve this by using @PaulMcKenzie's suggestion in the comments of your original question.
const MyString& MyString::operator = (const MyString& Obj)
{ MyString temp(Obj);
std::swap(temp.str, str);
std::swap(temp.length, length);
return *this;
}
|
70,487,931 | 70,488,073 | Arduino serial read and check | I am trying to learn some things about arduino serial reading from a bluetooth device. This is the code I found everywhere:
int incomingByte = 0; // for incoming serial data
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}
void loop() {
// send data only when you receive data:
if (Serial.available() > 0) {
// read the incoming byte:
incomingByte = Serial.read();
// say what you got:
Serial.print("I received: ");
Serial.println(incomingByte);
}
}
When I send the word "word" from my mobile bluetooth I get 4 lines:
I received: w
I received: o
I received: r
I received: d
which is fine... But here 's my question:
I want to check the received characters as soon as they come into the serial input, so if one of them is the character "r", I would like an extra line to be printed in the Serial Monitor, something like: "wow, that was an r!"
So I add an if statement after the println(incomingByte) and my code is now like that:
Serial.print("I received: ");
Serial.println(incomingByte);
if (incomingByte == "r") {
Serial.println("wow, that was an r!");
}
That code never works, it 's like not having an "r" at all.
Could someone explain to me?
Thanks
| I think it is due to the usage of "r" instead of 'r'. The difference is that in first case you have string, which is char[], and in the second you have single char.
|
70,488,182 | 70,488,302 | How to pass an empty span object? | Is there a way to pass an empty std::span<int> to a function?
I have a function like below:
bool func( const std::vector<int>& indices )
{
if ( !indices.empty( ) )
{
/* do something */
}
...
}
// when calling it with an empty vector
const bool isAcceptable { func( std::vector<int>( 0 ) ) };
And I want to change it to use std::span instead of std::vector so that it can also get std::array and raw array as its argument.
Now here:
bool func( const std::span<const int> indices )
{
if ( !indices.empty( ) )
{
/* do something */
}
...
}
// when calling it with an empty span
const bool isAcceptable { func( std::span<int>( ) ) }; // Is this valid code?
Also does std::span properly support all contiguous containers (e.g. std::vector, std::array, etc.)?
| std::span's default constuctor is documented as:
constexpr span() noexcept;
Constructs an empty span whose data() == nullptr and size() == 0.
Hence, passing a default constructed std::span<int>() is well-defined. Calling empty() on it is guaranteed to return true.
Does std::span properly support all contiguous containers (e.g. std::vector, std::array, etc.)?
Basically, std::span can be constructed from anything that models a contiguous and sized range:
template<class R>
explicit(extent != std::dynamic_extent)
constexpr span(R&& range);
Constructs a span that is a view over the range range; the resulting span has size() == std::ranges::size(range) and data() == std::ranges::data(range).
In particular, std::vector does satisfy these requirements.
For C-style arrays and std::array there are special constructors (to harness their compile-time size):
template<std::size_t N>
constexpr span(element_type (&arr)[N]) noexcept;
template<class U, std::size_t N>
constexpr span(std::array<U, N>& arr) noexcept;
template<class U, std::size_t N>
constexpr span(const std::array<U, N>& arr) noexcept;
Constructs a span that is a view over the array arr; the resulting span has size() == N and data() == std::data(arr).
|
70,488,184 | 70,488,220 | Strange behavior of reference in c++ | I'm little confused about reference type in c++, here goes my code snippet.
class data
{
public:
std::vector<int> Get() const
{
return vec;
}
private:
std::vector<int> vec = {1,2,3,4};
};
int main()
{
data dat;
auto const& a = dat.Get()[1];
auto const& b = dat.Get()[2];
std::cout << "a = " << a << ", b = " << b << std::endl;
return 0;
}
The output a = 0, b = 1433763856 doesn't make any sense, after I remove the leading & before a and b, everything works fine. Now here goes my questions:
Since reference of reference is not allowed, but vector::operator[] do return a reference of element inside container, why no error thrown?
I know data::Get() function causes deep copy, but why I get the wrong value of a and b? Will the return value be destroyed right after function call?
| You return a copy of the vector, as the signature
std::vector<int> Get() const
implies, as opposed to
std::vector<int> /*const*/& Get() const
which would return a reference, this is true, but that doesn't really explain why returning a copy is a mistake in this situation.
After all, if the call was
auto const& v = data.Get(); // *your* version here, the one returning by copy
v would not be dangling.
The point is that you're not keeping that copy alive by bounding it to a reference (as I've done in the last snippet).
Instead, you're calling operator[] on that temporary, and that call results in a reference to an entry (int&) in that vector. When the temporary vector returned by dat.Get() is destroyed, that's the reference which dangles.
If operator[] returned by value, then not even the a and b in your example would dangle.
|
70,488,236 | 70,488,627 | How do i make a function with a variable number of parameters? | I have a function:
vector<int> prime(int num, ...) {
vector<int> mas;
va_list args;
va_start(args, num);
for (int i = 0; i < num; i++) {
int v = va_arg(args,int);
if (isPrime(v)){
mas.push_back(v);
}
}
cout << endl;
va_end(args);
return mas;}
It should detected prime numbers.
But when i call it, part of my numbers, don`t get over.
It looks something like this
Input: 5, 7, 10, 15, 20,12, 13,16,19
Numbers what cout returns in the loop: 7,7
Help pls!
| First of all Variadic arguments from C are considered a bad practice in C++ and should be avoided.
There are plenty of better C++ solutions which are able to replace this C feature.
Old fashioned std::vector:
std::vector<int> filterPrimes(std::vector<int> a) {
auto end = std::remove_if(a.begin(), a.end(), [](auto x) {
return !isPrime(x)
};
a.remove(end, a.end());
return a;
}
Or std::initializer_list
std::vector<int> filterPrimes(std::initializer_list<int> l) {
std::vector<int> r;
std::copy_if(l.begin(), l.end(), std::back_inserter(r), isPrime);
return r;
}
Or Variadic templates, or template with iterator ranges, or ... .
|
70,488,470 | 70,537,160 | How to ignore compiler warnings for macros defined in third-party headers? | Currently it's possible to tell the compiler to ignore warnings from a given header by considering it a "system header", including the header via -isystem /path/to/dir.
However, this still won't work if the warning stems from a macro defined in such a header. Is there any way to ignore warnings also for macros? I'm mostly interested in GCC and Clang solutions.
Examples below are based on Clang 14.0.0 and GCC 11.1.0 on Ubuntu 20.04:
// include/third_party.h
#pragma once
#define MY_CAST(x) ((int)x)
// main.cpp
#include <third_party.h>
int main()
{
int x = MY_CAST(123);
return x;
}
With GCC:
$ g++ -isystem include -Wold-style-cast main.cpp
In file included from main.cpp:1:
main.cpp: In function ‘int main()’:
main.cpp:5:21: warning: use of old-style cast to ‘int’ [-Wold-style-cast]
5 | int x = MY_CAST(123);
| ^~~
With Clang:
$ clang++ -isystem include -Wold-style-cast main.cpp
$
Example that works with GCC but not with Clang:
// include/third_party2.h
#pragma once
struct Foo
{
int x;
int y;
};
#define FOO Foo{.x = 123, .y = 321}
// main.cpp
#include <third_party2.h>
int main()
{
Foo f = FOO;
return f.x;
}
$ g++ -isystem include -pedantic main2.cpp
$
$ clang++ -isystem include -pedantic main2.cpp
main2.cpp:5:13: warning: designated initializers are a C++20 extension [-Wc++20-designator]
Foo f = FOO;
^
include/third_party2.h:9:17: note: expanded from macro 'FOO'
#define FOO Foo{.x = 123, .y = 321}
^
1 warning generated.
| The issue seems to be simply a bug in GCC/Clang. In general, warnings are expected to be ignored when coming from system macros, and most of them are ignored. I just happen to have come across very concrete use cases where the warning is not ignored.
In case someone is interested in the GCC issue, here's the bug report:
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=103862
For Clang, I've asked a general question here:
https://lists.llvm.org/pipermail/cfe-dev/2021-December/069648.html
And reported issue here:
https://github.com/llvm/llvm-project/issues/52944
Bonus: for clang-tidy, I have a patch to make sure warnings from macros are ignored:
https://reviews.llvm.org/D116378
Thanks everyone for contributing to this investigation!
|
70,488,711 | 70,508,398 | Create opengl context in SDL and C++ using singleton pattern | I'm trying to create a simple window with SDL and OpenGL using singleton pattern, but when I execute the code appears a white window and the usage of VGA does not increase also, any of the error handlers get nothing which means everything worked well.
Here when I take off the SDL_GetError comment I get the following error on the screen: Invalid Window, but it only appears in the loop
Main.cpp
#include <SDL2/SDL.h>
#include <glad/glad.h>
class StartScreen
{
public:
int SCREEN_WIDTH = 800;
int SCREEN_HEIGHT = 800;
private:
static StartScreen *sInstance;
SDL_GLContext context;
static bool sInitialized;
SDL_Window *window = nullptr;
public:
static StartScreen *Instance()
{
if (sInstance == nullptr)
{
sInstance = new StartScreen();
}
return sInstance;
};
static void Release()
{
delete sInstance;
sInstance = nullptr;
sInitialized = false;
};
static bool Initialized()
{
return sInitialized;
};
void Render()
{
// SDL_GetWindowSize(window, &SCREEN_WIDTH, &SCREEN_HEIGHT);
// glViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
glClearColor(250.0f / 255.0f, 119.0f / 255.0f, 110.0f / 255.0f, 1.0f);
glClearDepth(1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
SDL_GL_SwapWindow(window);
};
private:
StartScreen()
{
sInitialized = Init();
};
~StartScreen()
{
SDL_DestroyWindow(window);
SDL_GL_DeleteContext(context);
window = nullptr;
SDL_Quit();
};
bool Init()
{
SDL_Log("%s", SDL_GetError());
if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
{
return false;
}
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 6);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_Log("%s", SDL_GetError());
SDL_Window *window = SDL_CreateWindow("Minecraft Clone",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
SDL_Log("%s", SDL_GetError());
if (window == NULL)
{
SDL_Log("Nao foi possivel criar a janela");
return false;
}
context = SDL_GL_CreateContext(window);
if (context == nullptr)
{
SDL_Log("Nao foi possivel inciar o contexto opengl");
}
SDL_Log("%s", SDL_GetError());
if (!gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress))
{
SDL_Log("Falha ao iniciar o glad");
return false;
}
glViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
SDL_Log("%s", SDL_GetError());
return true;
};
};
StartScreen *StartScreen::sInstance = nullptr;
bool StartScreen::sInitialized = false;
class Manager
{
private:
static Manager *sInstance;
bool mQuit;
StartScreen *mStart;
SDL_Event mEvents;
public:
static Manager *Instance()
{
if (sInstance == nullptr)
sInstance = new Manager();
SDL_Log("%s", SDL_GetError());
return sInstance;
};
static void Release()
{
delete sInstance;
sInstance = nullptr;
};
void Run()
{
while (!mQuit)
{
if (SDL_PollEvent(&mEvents))
{
if (mEvents.type == SDL_QUIT)
{
mQuit = true;
return;
}
}
mStart->Render();
SDL_Log("%s", SDL_GetError());
}
};
private:
Manager()
{
mQuit = false;
mStart = StartScreen::Instance();
SDL_Log("%s", SDL_GetError());
};
~Manager()
{
Manager::Release();
mStart = nullptr;
};
};
Manager *Manager::sInstance = nullptr;
int SDL_main(int argc, char *argv[])
{
Manager *game = Manager::Instance();
game->Run();
Manager::Release();
game = nullptr;
return 0;
}
| On the render function, I just needed to change the SDL_GL_SwapWindow reference that was SDL_GL_SwapWindow(window) that was referring to the window of the class StartScreen to SDL_GL_SwapWindow(SDL_GL_GetCurrentWindow()). I believe the reference has been lost since this function it's just used in other class (Manager), so this way the things are kind of global in the interns of the framework
|
70,489,004 | 70,489,108 | Overloading member operator,? | #include <iostream>
#include <vector>
struct Matrix;
struct literal_assignment_helper
{
mutable int r;
mutable int c;
Matrix& matrix;
explicit literal_assignment_helper(Matrix& matrix)
: matrix(matrix), r(0), c(1) {}
const literal_assignment_helper& operator,(int number) const;
};
struct Matrix
{
int rows;
int columns;
std::vector<int> numbers;
Matrix(int rows, int columns)
: rows(rows), columns(columns), numbers(rows * columns) {}
literal_assignment_helper operator=(int number)
{
numbers[0] = number;
return literal_assignment_helper(*this);
}
int* operator[](int row) { return &numbers[row * columns]; }
};
const literal_assignment_helper& literal_assignment_helper::operator,(int number) const
{
matrix[r][c] = number;
c++;
if (c == matrix.columns)
r++, c = 0;
return *this;
};
int main()
{
int rows = 3, columns = 3;
Matrix m(rows, columns);
m = 1, 2, 3,
4, 5, 6,
7, 8, 9;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
std::cout << m[i][j] << ' ';
std::cout << std::endl;
}
}
This code is inspired by the matrix class in the DLib library.
This code allows for assigning literal values separated by commas like this:
Matrix m(rows, columns);
m = 1, 2, 3,
4, 5, 6,
7, 8, 9;
Note that you can't do something like this:
Matrix m = 1, 2, 3, ...
This is because the constructor can't return a reference to another object, unlike the operator=.
Here in this code, if literal_assignment_helper::operator, is not const, this chaining of numbers doesn't work, the comma-separated numbers are considered to be comma-separated expressions.
Why must the operator be const? What are the rules here?
Also, what is the impact of an operator, that is not const? Is it ever going to be called?
| const literal_assignment_helper& operator,(int number) const;
The comma operators, both in the helper and in the Matrix, return a const reference. So to call a member on that reference, the member function/operator has to be const qualified.
If you remove all the constness, like
literal_assignment_helper& operator,(int number);
that also seems to work.
|
70,489,061 | 70,724,051 | undefined symbol: _PyThreadState_Current when using pybind wrapped C++ code | When I'm running bazel test ... the cpp code will compile, but Python gets stuck.
I read these before I wrote this question, but I can not find any solution:
https://github.com/pybind/pybind11/issues/314
undefined symbol: _PyThreadState_Current when importing tensorflow
https://github.com/carla-simulator/ros-bridge/issues/368
https://python-forum.io/thread-32297.html
OS:
Linux 5.11.0-43-generic #47~20.04.2-Ubuntu SMP Mon Dec 13 11:06:56 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux
Python: Python 3.8.10
g++: g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
pybind11: v2.8.1
C++ Code:
//math.cc
#include <pybind11/pybind11.h>
int add(int i, int j) {
return i + j;
}
int subtract(int i, int j) {
return i - j;
}
namespace py = pybind11;
PYBIND11_MODULE(math, m) {
m.def("add", &add);
m.def("subtract", &subtract);
}
Python code:
#math_test.py
from module import t_math
assert t_math.add(1, 1) == 2
assert t_math.subtract(1, 1) == 0
BUILD :
load("@pybind11_bazel//:build_defs.bzl", "pybind_extension")
pybind_extension(
name = "t_math",
srcs = ["math.cc"],
)
py_test(
python_version = "PY3",
name = "math_test",
size = "small",
srcs = ["math_test.py"],
data = [":t_math.so"],
)
error :
Traceback (most recent call last): File
"/home/user/.cache/bazel/_bazel_user/a768e2cde210bf677ee66cfded678e04/sandbox/linux-sandbox/52/execroot/main/bazel-out/k8-fastbuild/bin/module/math_test.runfiles/main/module/math_test.py",
line 7, in
from module import t_math ImportError: /home/user/.cache/bazel/_bazel_user/a768e2cde210bf677ee66cfded678e04/sandbox/linux-sandbox/52/execroot/main/bazel-out/k8-fastbuild/bin/module/math_test.runfiles/main/module/t_math.so:
undefined symbol: _PyThreadState_Current
| There were two problems:
the first parameter of the PYBIND11_MODULE macro must be the same as in the pybind_extension
this environment variable must be set to: PYTHON_BIN_PATH=$(which python3)
fixed example
# BUILD
load("@pybind11_bazel//:build_defs.bzl", "pybind_extension")
pybind_extension(
name = "new_math",
srcs = ["ex.cpp"],
)
py_test(
python_version = "PY3",
name = "math_test",
size = "small",
srcs = ["math_test.py"],
data = ["new_math.so"],
)
// ex.cpp
#include <pybind11/pybind11.h>
int add(int i, int j) {
return i + j;
}
int subtract(int i, int j) {
return i - j;
}
namespace py = pybind11;
PYBIND11_MODULE(new_math, m) {
m.def("add", &add);
m.def("subtract", &subtract);
}
# math_test.py
from module import new_math
assert new_math.add(1, 1) == 2
assert new_math.subtract(1, 1) == 0
|
70,489,194 | 70,490,220 | Is it "correct" to specify class-member mutex 'mutable' for the purpose of much-more 'const' member functions? | In many cases, many member-functions could be specified 'const' - they don't modify any data-members of the class ...almost: they do lock/unlock the class mutex. Is it a good practice to specify, in that case, the mutex 'mutable'? ...otherwise, it will impossible to specify get_a(), get_b(), get_c(), get_d() 'const'.
--
A mere example. Lets say that 'example' is a thread-safe class and that m_mutex protects its shared resources that get_a(), get_b(), get_c(), get_d() do not modify:
#include <mutex>
class example
{
public:
size_t get_a(void) const {
std::lock_guard lck(m_mutex);
return m_str.length() + a;
};
size_t get_b(void) const {
std::lock_guard lck(m_mutex);
return m_str.length() * 2 + a + b;
};
size_t get_c(void) const {
std::lock_guard lck(m_mutex);
return m_str.length() * 4 + a + b;
};
size_t get_d(void) const {
std::lock_guard lck(m_mutex);
return m_str.length() * 8 + a;
};
void modify_something() {
std::lock_guard lck(m_mutex);
if (m_str.length() < 1000) {
m_str.append(".");
a++;
b++;
}
};
protected:
mutable std::mutex m_mutex;
std::string m_str;
int a = 0, b = 0;
};
| Not only is this correct, but also standard practice. A member mutex is described as "non observably non-const", which means it behaves as a constant to a "user" observer.
Herb Sutter has popularized the M&M rule:
For a member variable, mutable and mutex (or atomic) go together.
The rule's section related to your question states:
For a member variable, mutex (or similar synchronization type) implies mutable: A member variable that is itself of a synchronization type, such as a mutex or a condition variable, naturally wants to be mutable, because you will want to use it in a non-const way (e.g., take a std::lock_guard<mutex>) inside concurrent const member functions.
The linked article has many code examples and further elaboration, should you want to dive deeper.
|
70,489,196 | 70,489,344 | How could I get address of the target object in smart pointer? | I'm trying to implement the linked list by indirect pointer, which introduced on the TED Talk.
I refer to felipec's implementation on github and made an version by raw pointer, this is the github link.
This is part of the full code, _find is a function that can find the indirect pointer of target node, which means *indirect == target node :
//...
struct Node {
int data;
Node *next;
Node()
: data(0), next(nullptr) {}
Node(int _d, Node *_next = nullptr)
: data(_d), next(_next) {}
~Node() { puts("~Node"); }
};
//...
List::Node **List::_find(const int target)
{
Node **indirect = &head;
while (*indirect && (*indirect)->data != target)
indirect = &(*indirect)->next;
return indirect;
}
I wanna make a smart pointer version of this. I use std::unique_ptr for the next pointer in Node, and std::shared_ptr for the head pointer in List.
But in the part Node **indirect = &head, I have no idea for how to design it by smart pointer, I have wrote this:
//...
struct Node {
int data;
std::unique_ptr<Node> next;
Node()
: data(0), next(nullptr) {}
Node(int _d, std::unique_ptr<Node> &_next)
: data(_d), next(std::move(_next)) {}
~Node() { puts("~Node"); }
};
//...
List::Node **List::_find(const int target)
{
Node **indirect = &(head.get());
while (*indirect && (*indirect)->data != target)
indirect = &(*indirect)->next;
return indirect;
}
Apparently, Node **indirect = &(head.get()) is not an good idea since the get function return a rvalue that it point to. But what I need is the pointer object that point to the target, the code even can't be compiled.
Thus, there is two question
How could I get the address of the target object in smart pointer?
Did I use the smart pointer in correct way? Should I change shared_ptr to unique_ptr, or just not use smart pointer for it?
Any additional supplements and recommendations are appreciated.
|
How could I get the address of the target object in smart pointer?
I think you mean "the address of the pointer in the smart pointer", because the address of the target object is just what you get with .get(). std::unique_ptr does not offer any interface to access it's pointer member directly, so it is impossible.
Did I use the smart pointer in correct way? Should I change shared_ptr to unique_ptr, or just not use smart pointer for it?
Using std::unique_ptr is the correct thing to do. You don't need shared_ptr because there are never two owners of any given node.
In your first code indirect is a pointer to a raw pointer in the Node/List structure. Since you changed these to smart pointers, indirect should also become a pointer to a smart pointer:
std::unique_ptr<List::Node> *List::_find(const int target)
{
std::unique_ptr<Node> *indirect = &head;
while (*indirect && (*indirect)->data != target)
indirect = &(*indirect)->next;
return indirect;
}
Although it would be more idiomatic to return a reference instead:
std::unique_ptr<List::Node> &List::_find(const int target)
{
std::unique_ptr<Node> *indirect = &head;
while (*indirect && (*indirect)->data != target)
indirect = &(*indirect)->next;
return *indirect;
}
(I am assuming that this is a private helper function and not actually the interface of the List class, in which case there would be problems with either implementation.)
|
70,489,820 | 70,490,278 | Getting a pointer with auto deduced return type on function template with default template argument | The following program makes the pointer x on function g<void>() having automatically deduced return type:
template<class=void>
void g() {}
int main() {
auto (*x)() = &g;
(*x)();
}
The program is accepted by GCC, but rejected in Clang with the error:
error: variable 'x' with type 'auto (*)()' has incompatible initializer of type '<overloaded function type>'
auto (*x)() = &g;
Demo: https://gcc.godbolt.org/z/s17Mf74Wc
Which compiler is right here?
| This code
auto (*x)() = &g;
should be legal as per the changes made by P1972, in particular the change to temp.deduct#funaddr-1
... If there is a target, the The function template's function type and the specified target type are used as the types of P and A, and the deduction is done as described in 13.10.2.5. Otherwise, deduction is performed with empty sets of types P and A.
I've emphasized the text that was added in P1972. Note that now, if there is no specified target type, as in the case auto (*)() since the return type of this function is deduced, template argument deduction can still be performed. Previously, without a target type, the template arguments couldn't be deduced when taking the address of g.
Of course, if the template arguments to g are specified, or the target type is specified, then it was always ok
void (*x)() = &g; // ok, target is specified
auto (*x)() = &g<void>; // ok, template parameters specified
Clang doesn't support P1972 yet, hence the error.
|
70,490,249 | 70,490,287 | C++ overload >> operator with different interaction based on which side of >> | I was wondering if it is possible to have overload the C++ >> operator in this way
Account& operator>> (double left, Account &right)
{
right.deposit(left);
return right;
}
Account& operator>> (Account &left, double right)
{
left.withdraw(right);
return left;
}
I was wondering if the >> operator had this functionality
so I could do something like this
account1 >> 200 >> account2
Which would withdraw 200 from the first account and then deposit it into the second account.
| As described, this is not going to work for the following simple reason:
account1 >> 200 ...
When this gets evaluated this ends up calling the following overload:
Account& operator>> (Account &left, double right)
Your attention is drawn to the fact that this overload returns an Account &. That's declared right there, in black and white. Let's keep going:
... >> account2
And now, the left-hand side of this operator>> is now an Account &, what the overload returned. It is not a double anymore. And it needs to be a double in order for the other overload to pick up the slack, and bring it home. That's how overloaded operators work in C++.
The simplest solution is probably to simply return a double value from the first overload:
double operator>> (Account &left, double right)
{
left.withdraw(right);
return right;
}
Now the result of this expression is a double value, which will have a much easier time getting the other overloaded operator>> to come into picture.
|
70,490,333 | 70,490,440 | Constructor in double inheritance | I have a problem with my constructor. I have class vehicle, then I made class motorVehicle which inherited after vehicle and then I want to make class motorcycle which inherits after class motorVehicle and I can't make my default constructor because I have error:
Class vehicle and motorVehicle isn't changed by me and class motorcycle is in 2 option none of these option works but I give you both of them. Btw the problems are (First option): no matching constructor for initialization of 'motorVehicle' and with second option expected ; after expression and expected member name or ; after declaration specifiers
class vehicle {
public:
int numberOfWheels;
string color;
float vehiclePayload;
vehicle(): numberOfWheels{4},color{"black"},vehiclePayload{500}{
}
};
class motorVehicle : public vehicle {
public:
float tankCapacity;
float fuelConsumption;
float mileage;
float currentAmountOfFuel;
int yearOfProduction;
unsigned long long int vin;
motorVehicle(): tankCapacity{30}, fuelConsumption{6}, mileage{100}, currentAmountOfFuel{10}, yearOfProduction{2021}, vin{1}, vehicle{4, "black", 500} {
}
};
class motorcycle : public motorVehicle{
public:
float bootSize;
string brand;
string model;
motorcycle(): bootSize{500}, brand{"Ninja"}, model{"Kawasaki"}, motorVehicle{30,6,100,10,2021,1,vehicle{4, "black", 500}}{
}
};
class motorcycle : public motorVehicle{
public:
float bootSize;
string brand;
string model;
motorcycle(): bootSize{500}, brand{"Ninja"}, model{"Kawasaki"}, motorVehicle(){30,6,100,10,2021,1,vehicle{4, "black", 500}}{
}
};
| Your base classes do not declare any constructor taking actual values. As these classes do declare a default constructor, aggregate initialisation doesn't work: there is a declared constructor, i.e., the class isn't an aggregate. If you want to directly initialise the base class you could use their implicitly generate copy constructor, though. However, you'd still need to populate the content of the class separately as you'll need to created the object using a default constructor:
class motorVehicle : public vehicle {
public:
float tankCapacity;
float fuelConsumption;
float mileage;
float currentAmountOfFuel;
int yearOfProduction;
unsigned long long int vin;
motorVehicle(): tankCapacity{30}, fuelConsumption{6}, mileage{100}, currentAmountOfFuel{10}, yearOfProduction{2021}, vin{1},
vehicle([]{
vehicle rc;
rc.numberOfWheels = 4;
rc.color = "black";
rc vehiclePayload = 500;
return rc;
}()) {
}
};
Obviously, instead of using a lambda function you could have a factor function, let's say makeVehicle(int wheels, std::string const& color, float payload) appropriately initialising the members. There should really be a suitable constructor for vehicle, though.
|
70,490,584 | 70,490,627 | Having trouble with class in c++ | I'm obviously making a mistake here, but please help me.
#include <iostream>
#include <string>
using namespace std;
int main()
{
class Item
{
int Value;
int Use_On(Entity Target)
{
Target.HP += Value;
}
};
class Entity
{
int HP;
Item Slot;
};
}
The Item class have a function that change the HP value of an Entity object, and the Entity class
have an Item object. This result in an error because Entity wasn't declared yet.
I've tried to make a prototype of the Entity class and declare it before the Item class, but this just result in another error saying Entity is an incomplete type. How can I solve this?
Also, sorry for the title, I'm not really good at english :|
| The solution is to forward-declare the class, declare the class method first, and define it only after all classes have been declared.
class Entity;
class Item
{
int Value;
int Use_On(Entity Target);
};
class Entity
{
int HP;
Item Slot;
};
int Item::Use_On(Entity Target)
{
Target.HP += Value;
}
See your C++ textbook for a complete discussion and explanation of forward reference, and the details of the alternative ways to declare and define class methods.
This should solve the immediate compilation error, but there are multiple other problems with the shown code that you will need to fix.
Use_On is declared as returning an int, but does not return anything.
In C++ parameters get passed by value by default, which means that Use_On ends up modifying only its local parameter, and otherwise accomplishing absolutely nothing, whatsoever. Whatever object gets passed into this class method remains completely unchanged. You will need to change the code to pass the parameter either via a pointer or by reference. Your C++ textbook will also have a discussion on these topics.
Classes should be declared in global scope, instead of inside functions like main(), where some class features are not available.
|
70,491,020 | 70,491,058 | Destruction order between globals and static function locals | My understanding is that the order of destruction of objects with static storage duration is the inverse of the order of their initialization.
In this code snippet:
#include <iostream>
class LogValuesObj {
public:
LogValuesObj() {
std::cout << "LogValuesObj" << std::endl;
}
~LogValuesObj() {
std::cout << "~LogValuesObj" << std::endl;
}
};
void logValues() {
static LogValuesObj o;
std::cout << "logValues function called" << std::endl;
}
class EarlyInitLogValues {
public:
EarlyInitLogValues() {
std::cout << "EarlyInitLogValues" << std::endl;
logValues();
}
~EarlyInitLogValues() {
std::cout << "~EarlyInitLogValues" << std::endl;
}
};
EarlyInitLogValues e;
int main() {
return 0;
}
The output on my compiler is:
EarlyInitLogValues
LogValuesObj
logValues function called
~EarlyInitLogValues
~LogValuesObj
In this case, the destruction order is the same as the init order, I expected it to be reversed. If both the global 'e' and the function static local 'o' have static storage duration, why is the destruction order not reversed?
| It is well-known that objects with static storage duration are destroyed in the reverse order of their construction. But to be more specific—and since it matters in your case—they are destroyed in the reverse order of the completion of their initialization. See [basic.start.term]/3.
In your case, the initialization of o will complete before the initialization of e. Therefore, e is destroyed before o.
|
70,491,088 | 70,491,106 | why doesn't assignment of int to std::map<string,string> produce a compiler error | Attempting to assign an int to a string
std::string s = 5;
produces the following compiler error:
error: conversion from ‘int’ to non-scalar type ‘std::string’ {aka ‘std::__cxx11::basic_string<char>’} requested
however assigning an int to the value of a string in a map doesn't. For example the below code compiles, and worse yet makes the assignment converting the int to a char
map <string, string>m;
m["test"] = 5;
Shouldn't this be an error?
| This shouldn't be an error. m["test"] = 5; performs assignment, and std::string has an assignment operator taking char, and int could be converted to char implicitly.
constexpr basic_string& operator=( CharT ch );
On the other hand, std::string s = 5; is not assignment but initialization; and std::string doesn't have any constructors taking int or char.
|
70,491,171 | 70,491,208 | What is the rule for type deduction for assignment using brace initialization? | In the following code, to my surprise, the { } appears to create a default initialized instance of int rather than of A.
struct A {
int i = 1;
A() = default;
A& operator=(const A& a) {
this->i = a.i;
return *this;
}
A& operator=(int i) {
this->i = i;
return *this;
}
};
int main() {
A a;
a = { };
return a.i;
}
What rule is used to parse a = { }? I thought that a = { } would have to be equivalent to a = decltype(a){ }.
What is the right term for the type of initialization that takes place here?
Here's an example on godbolt. At -O0 the assembly shows exactly which function is being used. Unless the int assignment operator is removed, A::operator=(int) is called.
| Firstly, the braced-init-list {} could be used to initialize both int and A, which are also considered as conversion, and the conversion from {} to int wins in overload resolution, since the conversion from {} to A (via A::A()) is considered as a user-defined conversion.
Assignment operator is not special, compilers just collect all the viable operator=s in overload set, then determine which one should be selected by overload resolution. If you add another operator=(float) you'll get an ambiguous error since conversion from {} to int and from {} to float are both considered as standard conversion with same rank, which wins against user-defined conversion.
|
70,491,371 | 70,502,232 | Why the number stuck and doesn't increase anymore? | first of all, i'm new in programming.
This is just a simple fun project for me, but i met unexpectedly problem and i don't know why.
Background: This is something like "Groundhog Day", start loop from a month, by next loop the time decrease by one second. I'm trying to calculate the total years (by counting the total seconds).
Here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int loop=1;
double secondsInDay = 60*60*24; //86400
double secondsInMonth = 86400*30; //2592000
float secondsInLoop = 86400*30;
double totalYears = 0;
long totalSeconds = 0;
cout <<"Loop : "<<loop<<endl;
totalSeconds += secondsInLoop;
cout <<"-> Total seconds: "<<totalSeconds<<endl;
cout <<fixed<<setprecision(0)<<"-->Total time in this Loop: "<<secondsInLoop;
cout <<fixed<<setprecision(3)<<" seconds / "<<secondsInLoop/60<<" minutes / "<<secondsInLoop/3600<<" hours / "<<secondsInLoop/86400<<" days"<<endl<<endl;
while (secondsInLoop>0)
{
if (loop%1000==0)
{
cout <<"Loop: "<<loop<<endl;
cout <<"-> Total Seconds: "<<totalSeconds<<endl;
cout <<fixed<<setprecision(0)<<"-->Total time in this Loop: "<<secondsInLoop;
cout <<fixed<<setprecision(3)<<" seconds / "<<secondsInLoop/60<<" minutes / "<<secondsInLoop/3600<<" hours / "<<secondsInLoop/86400<<" days"<<endl;
totalYears = totalSeconds/(secondsInMonth*12); //31104000
cout <<fixed<<setprecision(3)<<"-->> Total Years: "<<totalYears<<endl<<endl;
}
totalSeconds = totalSeconds+secondsInLoop;
secondsInLoop--;
loop++;
}
cout <<"Loop: "<<loop<<endl;
cout <<"#-> Total Seconds: "<<totalSeconds<<endl;
totalYears = totalSeconds/(secondsInMonth*12); //31104000
cout <<"#->> Total Years: "<<totalYears<<endl<<endl;
return 0;
}
Problem: In my code, in about loop 2461000, the Total Seconds is stuck and doesn't increase anymore.
It's weird because the stuck number is 3359234850816, and it's far from the max number of long type.
And, if i try to calculate normally (in another simple arithmetic code) there is no stuck like that.
Can anyone help please?
Also, i'm open to any suggestion for tidy it up, or anything for the matter. Thanks
| You've surpassed the limits of your chosen numeric representation.
This might be surprising since most of the time, when mixing numeric types, C++ will convert to the type that can best represent the result. For example, adding an int and long long is calculated as a long long. Adding a float and double is calculated as a double. However, you've chosen one of the odd routes by adding an integer type and a float.
By the usual arithmetic conversions, adding any integer type and a float is calculated as a float. Any integer type. If you happen to have a 128-bit long long and a 32-bit float, adding them produces a 32-bit float. The float is treated as if it can better represent numbers, which has merit. A typical 32-bit float does have about the same range as a 128-bit integer, with the benefit of being able to represent non-integers. However, while this thinking might be behind the rule, the rule is simply that a float combined with an integer type produces a float.
Apply this to the line that updates totalSeconds.
totalSeconds = totalSeconds+secondsInLoop;
While totalSeconds is a long, secondsInLoop is a float. That means that when these are added, the result is a float. Presumably, this means a 32-bit value with 24 logical bits in the significand (23 real bits plus an assumed 1). This is the precision of the result. Only the most significant 24 bits of the sum are preserved. When your value stops increasing, the integer is 3359234850816 and the floating point value is 131071 (I ran your code to come up with this). The ratio of these values is 25629124, a 25-bit value. Compared to totalSeconds, the value of secondsInLoop is so small, it might as well be zero as far as float addition is concerned.
To get the correct calculation, you need to change the type of the result. The most straight-forward approach is to use long for all of your integer values, and just remember to cast to floating point before dividing. Another approach would be to change secondsInLoop to be a double (like your other floating point variables that hold integers—odd that you singled this one out). Since the typical double has 53 logical bits of precision, it can represent all 32-bit integers precisely. Thus, this problem is avoided (until you need to go to 64-bit integers...). You could also cast to an integer type in the sum, which overrides the conversion to floating point.
So
long secondsInLoop = 86400*30;
or
double secondsInLoop = 86400*30;
or
totalSeconds = totalSeconds + static_cast<long>(secondsInLoop);
will allow a more precise representation for your sum.
|
70,491,390 | 70,491,463 | Why does my c++ fibonacci sequence code give negative values after 46 iterations | The code also doesn't work whenever I try to take out the first two iterations out of the for loop. When I do, I get incredibly high numbers and then 0s for 11 iterations and my i value doesn't change. It has a vector size of 3 at the start of the loop for some reason as well, but it might have to do with the fact that it still wants to add together 0 + 0 for the first term. The error it makes is it adds the two correct values up and somehow ends up with a negative integer. This throws all other values off for the rest of the loop.
#include <iostream>
#include <vector>
int main(){
std::vector<int> vector;
vector.push_back(0);
vector.push_back(1);
for (int i=0; i <= 47; i++) {
if (i < 1) {
std::cout << vector[i] << ", \n";
}
vector.push_back(vector[i] + vector[i + 1]);
std::cout << vector[i] << " = " << vector[i-2] << " + " << vector[i-1] << ": " << "vector size" << vector.size() << ", \n";
}
}
| The negative values should have been a big hint to you. An int has a maximum value of 2147483647. You overflow the int and it wraps around to being negative.
If you use a bigger type, like std::uint64_t, you can postpone the overflow by a decent amount. Its maximum value is: 18446744073709551615.
Finally, printing in the loop creates a lot of repetition that can be hard to decipher. Just print your vector after the loop is complete, and test with a smaller number of iterations to ensure that your algorithm is functioning properly.
#include <cstdint>
#include <iostream>
#include <limits>
#include <vector>
int main() {
std::vector<std::uint64_t> vector{0, 1};
for (int i = 0; i < 47; i++) {
vector.push_back(vector[i] + vector[i + 1]);
}
for (auto i : vector) {
std::cout << i << ' ';
}
std::cout << '\n';
}
The for loop creating the sequence iterates 47 times, so double-check your requirements.
|
70,491,519 | 70,491,712 | How to properly specify a recursive template class member function? | I want to unpack a variadic template parameter pack. As the function requires access to private members of the object, I decided to write it as a member function. To my understanding, according to the standard, a template function has to be specified in the same namespace as the enclosing class, I tried to separate declaration and definition. As I result I only received lookup errors.
Below is a short recreation of what I'm trying to do:
class Container{
private:
//My first try
template<typename... Ts>
void foo();
//Second try
template<> foo();
template<typename T, typename... Ts>
void foo();
}
template<> void Container:foo(){}
template<typename T, typename... Ts>
void Container::foo(){
foo<Ts...>();
}
What am I supposed to write instead of the commented parts, or is there a more general mistake in how I'm trying this?
I already looked at questions like recursive variadic template to print out the contents of a parameter pack, but none of them used a member function, so it didn't really help sadly.
Also, this should just do nothing in case of an empty parameter list. Which is why the following didn't work.
template<typename T, typename... Ts>
void foo(){
if constexpr (sizeof...(Ts)){
foo<Ts...>();
}
}
About the error messages:
For try 1 -
Container::foo() does not match any template declaration
For try 2 -
explicit specialization in non-namespace scope class Container
| Your first try didn't work because the declaration template<typename... Ts> void foo(); has to be matched with a declaration that looks the same, not template<typename T, typename... Ts> void foo() { // ..., which has different template parameters.
In C++17, it is pretty simple to "do something" for each thing in a parameter pack using fold expressions:
class Container {
private:
template<typename... Ts>
void foo();
};
template<typename... Ts>
void Container::foo() {
// Fold over comma which calls and discards the result of a lambda
(([&]{
// Use `Ts` here. For example:
std::cout << typeid(Ts).name() << '\n';
}()), ...);
}
|
70,491,663 | 70,491,714 | Syntax error for the code found in a tutorial? | I was learning to do a program online and found this solution and I wanted to execute and learn from it.
I am keep getting syntax error, can someone help with formatting it? I tried but couldn't understand the code that much to see where we need to provide indentation etc.,
I couldn't find a python example online for that question, I could only find c++ answer.
class Node {
public:
virtual int Compute() = 0;
inline void SetLeft(Node* left) {
left_ = left;
}
inline void SetRight(Node* right) {
right_ = right;
}
protected:
Node* left_ = nullptr;
Node* right_ = nullptr;
};
class SumNode : public Node {
public:
inline int Compute() override {
return left_->Compute() + right_->Compute();
}
};
class SubNode : public Node {
public:
inline int Compute() override {
return left_->Compute() - right_->Compute();
}
};
class MulNode : public Node {
public:
inline int Compute() override {
return left_->Compute() * right_->Compute();
}
};
class NumNode : public Node {
public:
NumNode(int num) : num_(num) {}
inline int Compute() override {
return num_;
}
private:
int num_;
};
class Solution {
public:
vector<int> diffWaysToCompute(string expression) {
vector<Node*> nodes;
// parse the expression
for(int i = 0; i < expression.size(); ++i) {
switch(expression[i]) {
case '+':
nodes.emplace_back(new SumNode());
break;
case '-':
nodes.emplace_back(new SubNode());
break;
case '*':
nodes.emplace_back(new MulNode());
break;
default:
int num = 0;
while(expression[i] >= '0' && expression[i] <= '9') {
num = num * 10 + expression[i] - '0';
++i;
}
--i;
nodes.emplace_back(new NumNode(num));
break;
}
}
vector<Node*> trees = GenerateAllTrees(nodes, 0, nodes.size() - 1);
for(Node* node : nodes) {
delete node;
}
vector<int> results;
for(Node* tree : trees) {
results.emplace_back(tree->Compute());
delete tree;
}
return results;
}
vector<Node*> GenerateAllTrees(const vector<Node*> nodes, int beg, int end) {
if(beg == end) {
return {new NumNode(nodes[beg]->Compute())};
}
vector<Node*> results;
for(int i = beg; i <= end; i++) {
// assuming the expression is well formed, operators will be in odd positions
if((i & 1) == 0) continue;
vector<Node*> left_trees = GenerateAllTrees(nodes, beg, i - 1);
vector<Node*> right_trees = GenerateAllTrees(nodes, i + 1, end);
for(Node* left : left_trees) {
for(Node* right : right_trees) {
nodes[i]->SetLeft(left);
nodes[i]->SetRight(right);
Node* result = new NumNode(nodes[i]->Compute());
results.emplace_back(result);
}
}
for(Node* t : left_trees) {
delete t;
}
for(Node* t : right_trees) {
delete t;
}
}
return results;
}
};
| You just need to import the modules you are using, exactly like Python, except the syntax is different:
#include <vector>
#include <string>
using namespace std;
class Node {
public:
...
And because it is using emplace_back, if you are using g++, you'll need to specify -std=c++11 on the command line.
Also, you need to understand this is not a runnable example. These are just classes you could use in your own code. To run this, you'll need to supply a main() function. Maybe:
#include <iostream>
int main()
{
Solution s;
vector<int> result = s.diffWaysToCompute( "3+9*7-16" );
for( auto i : result )
cout << i << "\n";
}
|
70,492,586 | 70,566,658 | Swig: How to change the accessiblity of the generated C# classes from `public class` to `internal class` | I am using swig 4.0.x to wrap a c++ file.
Everything is working fine except I want to change the accessibility of the generated C# classes from public class to internal class.
So far what I have tried is this:
In swig interface file
%module example
%{
#include "include/exampleapi.h"
%}
%typemap(csclassmodifiers) SWIGTYPE "internal class"
%pragma(csharp) moduleclassmodifiers="internal class"
%include <windows.i>
%include "include/exampleapi.h"
The above code seems to work for the module class (example) and some other files. But it is not changing the accessibility modifier of all the generated classes.
Particularly, classes whose name starts with public class SWIGTYPE_xxx (probably known as proxy classes? These classes contain internal members and have a private member with type private global::System.Runtime.InteropServices.HandleRef) .
How do I make them internal class?
| Okay, so I have figured it out after asking this question on swig github repository. Following answer courtesy to William Fulton:
SWIGTYPE_xxx classes are called Type Wrapper Classes.
You need to use the C type for the typemap that causes the type wrapper class to be generated. For example SWIGTYPE_p_int is wrapping an int *. Hence you'd use:
%typemap(csclassmodifiers) int * "internal class"
The defaults for all generated proxy and type wrapper classes comes from csharp.swg:
%typemap(csclassmodifiers) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "public class"
So just override these typemaps to provide your customised code and read the chapter on Typemaps in the documentation.
|
70,492,992 | 70,493,691 | what is this + before u8 string literal prefix for? | when I was reading codecvt example in cppref, I noticed this line:
std::string data = reinterpret_cast<const char*>(+u8"z\u00df\u6c34\U0001f34c");
Any idea what is that + before u8 for? Because I removed it and nothing changed in result.
| The + is "explicitly" performing the array-to-pointer implicit conversion, producing a prvalue const char8_t* (or const char* before C++20), instead of an lvalue array.
This is unnecessary since reinterpret_cast<T> (when T is not a reference) performs this conversion anyways.
(Possibly it was used to prevent confusion with the similar reinterpret_cast<const char* const&>(u8"..."), which interprets the bytes of the array as a pointer, which is obviously not what was wanted. But I personally wouldn't worry about this)
|
70,493,226 | 70,493,994 | Is this a real problem: warning C4172: returning address of local variable or temporary | The following code drops the warning C4172: returning address of local variable or temporary under Windows with MSVC. But im wondering is it a real error in this case or not? I know there is lots of similar topic here, and i have read lots of similar topics here from this warning. So in this case the returning value is a pointer from "main" function which should be alive until the end of program. If returningLocalPointer would return: "A something; return &something;" then yes it would be a problem, but in this case we return a pointer which exists until "main" ending. Or am i wrong?
class A
{
};
A* returningLocalPointer(A* a)
{
return a;
}
template<typename T>
T const& doWarning(T const& b)
{
A* c = returningLocalPointer(b);
return c; // error if uses call-by-value
}
int main()
{
A d;
auto m = doWarning(&d); //run-time ERROR
}
| Yes, this is a real problem. Your program's behavior is undefined. c is a different object from the pointer referenced by b, and its lifetime ends at the end of doWarning. Those two pointers point to the same A object (d), but that doesn't mean they're the same object.
To illustrate, I'll go more-or-less line-by-line and use diagrams:
A d;
auto m = doWarning(&d);
This creates an A object named d and passes an anonymous pointer to that object to doWarning. I'll get to m later, but for now the objects in play look like this:
d
┌─────┐ ┌─────┐
│ │ │ │
│ A* ├──────►│ A │
│ │ │ │
└─────┘ └─────┘
template<typename T>
T const& doWarning(T const& b)
{
Here, T will be deduced to be A*, since that's what got passed to it.
doWarning accepts its parameter by reference, so the type of b will be A* const &. That is, b is a reference to the anonymous pointer to d from main:
b d
┌───────────┐ ┌─────┐ ┌─────┐
│ │ │ │ │ │
│ A* const& ├──────►│ A* ├──────►│ A │
│ │ │ │ │ │
└───────────┘ └─────┘ └─────┘
A* c = returningLocalPointer(b);
Here you create another pointer, c, that points to the same object as b. I won't look at returningLocalPointer, since it's more-or-less irrelevant. This line could be replaced with A* c = b; and nothing would change. Your objects now look like this:
b d
┌───────────┐ ┌─────┐ ┌─────┐
│ │ │ │ │ │
│ A* const& ├──────►│ A* ├──────►│ A │
│ │ │ │ │ │
└───────────┘ └─────┘ └─────┘
▲
c │
┌─────┐ │
│ │ │
│ A* ├──────────┘
│ │
└─────┘
As you can see, c is a different object than the object referenced by b.
return c;
Since doWarning returns an A* const& (since T is A*), this initializes the return value to refer to the local variable c:
b d
┌───────────┐ ┌─────┐ ┌─────┐
│ │ │ │ │ │
│ A* const& ├──────►│ A* ├──────►│ A │
│ │ │ │ │ │
└───────────┘ └─────┘ └─────┘
▲
return value c │
┌───────────┐ ┌─────┐ │
│ │ │ │ │
│ A* const& ├──────►│ A* ├──────────┘
│ │ │ │
└───────────┘ └─────┘
}
Now doWarning ends, and so its local variable c goes out of scope and its lifetime ends. That leaves doWarning's return value dangling:
b d
┌───────────┐ ┌─────┐ ┌─────┐
│ │ │ │ │ │
│ A* const& ├──────►│ A* ├──────►│ A │
│ │ │ │ │ │
└───────────┘ └─────┘ └─────┘
return value
┌───────────┐
│ │
│ A* const& ├──────► Nothing here anymore
│ │
└───────────┘
auto m = doWarning(&d);
Now we get back to m. auto by itself will never deduce a reference type, so the type of m is deduced to be A*. That means the program will attempt to copy the pointer referenced by the reference that doWarning returned. The pointer that doWarning's return value referenced no longer exists though. Trying to copy a nonexistent object is an error, and if a program does so its behavior is undefined.
|
70,493,707 | 70,493,935 | Symbol names convention in libstdc++ | During building a library I got the following "undefined reference" error:
libtbb.so.2: undefined reference to `__cxa_init_primary_exception@CXXABI_1.3.11'
When I checked the symbols in my libstdc++ library I saw the following
nm -CD libstdc++.so.6.0.24 | grep "__cxa_init_primary_exception"
000000000008fdd8 T __cxa_init_primary_exception@@CXXABI_1.3.11
So the only difference between the symbol name in libstdc++.so and what libtbb.so seems to require is an additional "@" in the symbol name. Even more interesting if I type
nm -C libtbb.so.2 | grep "__cxa_init_primary_exception"
U __cxa_init_primary_exception@@CXXABI_1.3.11
I see that libtbb requires a symbol which actually includes a double @. What's the ratio behind this naming convention and why does the linker search for a symbol name with one @?
| Maybe related to a known issue?
It's also mentioned here:
...current TBB has problems with gcc-libs, it’s compiled with gcc-libs 7.x so you will get this error if you try to build OpenCV with newest TBB
Proposed solution there:
This is also posted here, workaround is you should install TBB 2017_20170412-1 from Arch Linux Archive. To do this, first install newest TBB and then downgrade it.
|
70,494,146 | 70,495,302 | How to Pass an ATL com object from c++ to c# | using ATl i have created a com object called "Comptes" ,that has properties like name,username. this is the idl file for the atl project
import "oaidl.idl";
import "ocidl.idl";
[
object,
uuid(15297371-6D05-4466-B80D-26207555CD28),
dual,
nonextensible,
pointer_default(unique)
]
interface Icompte : IDispatch{
[propget, id(1)] HRESULT name([out, retval] BSTR* pVal);
[propput, id(1)] HRESULT name([in] BSTR newVal);
[propget, id(2)] HRESULT sername([out, retval] BSTR* pVal);
[propput, id(2)] HRESULT sername([in] BSTR newVal);
[propget, id(3)] HRESULT email([out, retval] BSTR* pVal);
[propput, id(3)] HRESULT email([in] BSTR newVal);
[propget, id(4)] HRESULT phone([out, retval] BSTR* pVal);
[propput, id(4)] HRESULT phone([in] BSTR newVal);
};
[
uuid(73A9DD4C-CE2D-4419-9F95-4A84C4E3B271),
version(1.0),
]
library ATLOBJECTSLib
{
importlib("stdole2.tlb");
[
uuid(1199A9AD-8AF7-4A25-A10B-DD06FB294B2E)
]
coclass compte
{
[default] interface Icompte;
};
};
i have inculded the header and cpp file in an c++ mfc project and was able to estantiate the com object ,now in the mfc project i am sending data to c# project (just simple strings)
this the mfc part :
void CmfcappDlg::OnBnClickedCreateacountbutt()
{
CoInitializeEx(nullptr, COINIT::COINIT_MULTITHREADED);
Icompte* pcompte;
HRESULT hr = CoCreateInstance(CLSID_compte,nullptr,CLSCTX_INPROC_SERVER,IID_Icompte,(LPVOID*)&pcompte);
if (SUCCEEDED(hr))
{
namectrl.GetWindowText(name);
sernamectrl.GetWindowText(sername);
emailctrl.GetWindowText(email);
phonectrl.GetWindowText(phone);
pcompte->put_name(name.AllocSysString());
pcompte->put_sername(sername.AllocSysString());
pcompte->put_phone(phone.AllocSysString());
pcompte->put_phone(email.AllocSysString());
//Managed::showcswindow(name, sername);
}
CoUninitialize();
}
now i can send the dat to the c# part with this class :
#include "stdafx.h"
#include "Managed.h"
#using <System.dll>
using namespace System;
using namespace ::gettingdatafromc;
void Managed::showcswindow(CString name,CString sername)
{
services::showwindow(gcnew String(name), gcnew String(sername));
}
and receive it in c# project with this class :
namespace gettingdatafromc
{
public static class services
{
public static void showwindow(string name, string sername)
{
}
}
}
everything works fine exept that i want to send the com object by passing it as a parameter to the showwindow method rather than a simple string to the c# project is this even dowable ,
| Try to pass raw IUnkown* pointer to C# and then use Marshal.GetObjectForIUnknown to convert IntPtr to object and then cast this object to Icompte. You will need to add reference to the corresponding TypeLib into C# project to be able to perform such a cast.
|
70,494,373 | 70,494,469 | Is there a way to remove the "int main{}" in C++ | I've searched some but only found subjects based on C and not C++, here.
So I was wondering whether there is a way to remove the main function using some weird function or something to shorten one's code.
The purpose of this is for code-golf, which is shortening one's code to the absolute shortest. I found the int main{} particularly annoying when code-golfing as it adds an additional 10 characters to my char count. Unlike other languages, e.g. python, C languages require this unfortunately. So is there a way to remove this to lower my char count?
Not only that, I think this can be applicable for things other than code-golf, especially if users do not want to use the entry point of int main{} for some reason.
| There are two ways.
The first is to build a library instead of an application. You can't run it, but it will build your code to a library that can be linked by other applications. In g++, for instance, you do this with:
g++ -c my_file.cc -o my_file.o
g++ -shared -o libmy_file.so my_file.o
The other way is to modify your linker script so that it uses an entry point other than main. It's not possible to do this in a way that conforms with the C++ standard, but most linkers will give you a way of doing it. See here for how to do it with the GNU linker, for instance.
|
70,494,426 | 70,494,557 | For constant expressions, why can't I use a use a pointer-type object, as standards says? | I was trying to figure out the restrictions of constexpr in cpp11/14. There are some usage requirements I found in CPP14-5.19-4:
A constant expression is either a glvalue core constant expression
whose value refers to an object with static storage duration or to a
function, or a prvalue core constant expression whose value is an
object where, for that object and its subobjects:
...
if the object or subobject is of pointer type, it contains the address of another object with static storage duration, the address past
the end of such an object (5.7), the address of a function, or
a null pointer value.
I've run some tests(code shown below) for expressions that involves address-of operator &, in order to ensure the correctness of the standards' statements quoted above.
Simply put, I tried to take the address of a global int variable global_var, which is an object with static storage duration(if I was not thinking wrong), everything works just as standards points out. But, what confused me is that, when I tried to assign another pointer-type object(global_var_addr1 in code), which stored the address of the same object global_var, the program won't compile. And GCC says:
error: the value of ‘global_var_addr1’ is not usable in a constant expression
note: ‘global_var_addr1’ was not declared ‘constexpr’
, while Clang-Tidy says:
error: constexpr variable 'x2' must be initialized by a constant expression [clang-diagnostic-error]
note: read of non-constexpr variable 'global_var_addr1' is not allowed in a constant expression
and I don't know why, is there anything I missed?
So my question is:
1. Why, in a constant expression, I cannot use a pointer-type object which contains the address of an object with static storage duration, as standards says?
2. Why everything goes different in the same context as (1), when the object is auto specified?
Any advices would be welcomed, thanks in advance!
Code:
const int global_var_c = 123;
int global_var = 123;
const void *global_var_addr1 = &global_var;
const void *global_var_addr2 = nullptr;
auto global_var_addr3 = nullptr;
auto main() -> int
{
constexpr const int x00 = global_var_c; // OK
constexpr const void *x0 = &global_var; // OK
// Operate on the object of pointer type
constexpr const void *x1 = &global_var_addr1; // OK
constexpr const void *x2 = global_var_addr1; // ERROR: read of non-constexpr variable 'global_var_addr1'...
// Operate on nullptr
constexpr const void *x3 = &global_var_addr2; // OK
constexpr const void *x4 = global_var_addr2; // ERROR: read of non-constexpr variable 'global_var_addr2'...
// Operate on nullptr (with type deduction)
constexpr const void *x5 = global_var_addr3; // OK
constexpr const void *x6 = &global_var_addr3; // OK
}
| In both
constexpr const void *x2 = global_var_addr1;
and
constexpr const void *x4 = global_var_addr2;
a lvalue-to-rvalue conversion happens from the variable global_var_addr1/global_var_addr2 glvalue to the pointer value they hold. Such a conversion is only allowed if the variable's lifetime began during the evaluation of the constant expression (not the case here) or if it is usable in constant expressions, meaning that it is constexpr (not the case here) or initialized by a constant expression (is the case here) and of reference or const-qualified integral/enumeration type (not the case here).
Therefore the initializers are not constant expressions.
This is different in the case of
constexpr const int x00 = global_var_c;
since global_var_c is of const-qualified integral type.
I am not exactly sure about
constexpr const void *x5 = global_var_addr3; // OK
Intuitively it should work, because the type of nullptr and consequently the deduced type of global_var_addr3 is std::nullptr_t which doesn't need to carry any state, so that a lvalue-to-rvalue conversion wouldn't be necessary. Whether the standard actually guarantees that, I am not sure at the moment.
Reading the current wording (post-C++20 draft), [conv.ptr] specifies only conversion of a null pointer constant (i.e. a prvalue of std::nullptr_t) to another pointer type and [conv.lval] specifically states how the lvalue-to-rvalue conversion of std::nullptr_t produces a null pointer constant. [conv.lval] also clarifies in a note that this conversion doesn't access memory, but I don't think that makes it not a lvalue-to-rvalue conversion given that it still written under that heading.
So it seems to me that strictly reading the standard
constexpr const void *x5 = global_var_addr3; // OK
should be ill-formed (whether global_var_addr3 is const-qualified or not).
Here is an open clang bug for this. There seems to be a link to come internal discussion by the standards committee, which I cannot access.
In any case, the auto placeholder doesn't matter. You could have written std::nullptr_t for it instead directly.
All of these are requirements for being a core constant expression, which is a prerequisite to the requirements you mention in your question.
|
70,494,728 | 70,495,272 | Performance of boost::mp11::mp_with_index compared to array of std::function | Consider the following two snippets:
// Option (1).
boost::mp11::mp_with_index<N>(i,
[&](const auto i){ function<i>(/* args... */); });
and
// Option (2).
inline static const std::array<std::function<void(/* Args... */)>, N>
functionArray{function<0>, ..., function<N-1>};
functionArray[i](/* args... */);
where N is a compile time size approximately in the range [0, 20], i is a runtime index between 0 and N-1, and template <size_t I> function(/* Args... */) is a template function with a known signature. Which of the two options is the fastest one?
Note: I know that boost::mp11::mp_with_index basically creates a switch statement that allows to convert a runtime index to a compile time one. This introduces some indirection, but I expect this to not be too costly. Similarly, I know that std::function introduces some indirection due to type erasure. My question is: which of the two indirection kinds is the most efficient?
| std::array<std::function<void(Args...)>, N> is likely to introduce some overhead compared to an array of pure pointers std::array<void(*)(Args...), N>.
Looking at the generated assembly at https://godbolt.org/z/a8z9aKs7P, the following observations can be made:
boost::mp11::mp_with_index is compiled to a branch table that holds N addresses for N different instructions that simply call function<I> when jumped to. So, it will look for an address in the branch table, jump to that address, and then jump again to the desired function.
This branch table could be simplified by having it simply store the addresses of function<I>, only needing one jump. This is what happens when you have an array of function pointers, the array essentially being a branch table.
std::function is similar, but calling a std::function is slightly more complicated than calling a regular function pointer.
Note clang is horrible at optimising this at -O2 and even -O3. boost::mp11::mp_with_index<N> is actually a bunch of if/else statements that should be very easy to compile as if it was a switch, but clang fails to do that (and left with N "compare and conditional jump" instructions). The array of function pointers is the only good option here.
|
70,495,138 | 70,525,475 | Why Eigen C++ with MKL doesn't use multi-threading for this large matrix multiplication? | I am doing some calculations that include QR decomposition of a large number(~40000 in each execution) of 4x4 matrix with complex double elements (chosen from a random distribution). I started with directly writing the code using Intel MKL functions. But after some research, it seems like working with Eigen will be much simpler and result in easier to maintain code. (Partly because I find it difficult to work with 2d arrays in intel MKL & care needed for memory management).
Before shifting to Eigen, I started with some performance checks. I took a code(from an earlier similar question on SO) for multiplications of a 10000x100000 matrix with another 100000x1000 matrix (large size chosen to have the effect of parallelization ). I run it on a 36 core node . When I checked the stat, Eigen without Intel MKL directive (but compiled with -O3 -fopenmp) used all the cores and completed the task within ~7 sec.
On the other hand with,
#define EIGEN_USE_MKL_ALL
#define EIGEN_VECTORIZE_SSE4_2
the code takes 28 s & uses an only a single core.
Here is my compilation instruction
g++ -m64 -std=c++17 -fPIC -c -I. -I/apps/IntelParallelStudio/mkl/include -O2 -DNDEBUG -Wall -Wno-unused-variable -O3 -fopenmp -I /home/bart/work/eigen-3.4.0 -o eigen_test.o eigen_test.cc
g++ -m64 -std=c++17 -fPIC -I. -I/apps/IntelParallelStudio/mkl/include -O2 -DNDEBUG -Wall -Wno-unused-variable -O3 -fopenmp -I /home/bart/work/eigen-3.4.0 eigen_test.o -o eigen_test -L/apps/IntelParallelStudio/linux/lib/intel64 -lmkl_intel_lp64 -lmkl_intel_thread -lmkl_rt -lmkl_core -liomp5 -lpthread
The code is here,
//#define EIGEN_USE_MKL_ALL // Determine if use MKL
//#define EIGEN_VECTORIZE_SSE4_2
#include <iostream>
#include <Eigen/Dense>
using namespace Eigen;
int main()
{
int n_a_rows = 10000;
int n_a_cols = 10000;
int n_b_rows = n_a_cols;
int n_b_cols = 1000;
MatrixXi a(n_a_rows, n_a_cols);
for (int i = 0; i < n_a_rows; ++ i)
for (int j = 0; j < n_a_cols; ++ j)
a (i, j) = n_a_cols * i + j;
MatrixXi b (n_b_rows, n_b_cols);
for (int i = 0; i < n_b_rows; ++ i)
for (int j = 0; j < n_b_cols; ++ j)
b (i, j) = n_b_cols * i + j;
MatrixXi d (n_a_rows, n_b_cols);
clock_t begin = clock();
d = a * b;
clock_t end = clock();
double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
std::cout << "Time taken : " << elapsed_secs << std::endl;
}
In the previous question related to this topic, the difference in speed was found to be turbo boost (& difference was not such huge). I know for small matrices Eigen may work better than MKL. But I can't understand why Eigen+MKL refuses to use multiple cores even when I pass -liomp5 during compilation.
Thank you in advance .
(CentOS 7 with GCC 7.4.0 eigen 3.4.0)
| Please set the following shell variables before executing you program.
export MKL_NUM_THREADS="$(nproc)"
export OMP_NUM_THREADS="$(nproc)"
Also the build command (the first line run with $define EIGEN_USE_MKL_ALL commented out)
. /opt/intel/oneapi/setvars.sh
$CXX -I /usr/local/include/eigen3 eigen.cpp -o eigen_test -lblas
$CXX -I /usr/local/include/eigen3 eigen.cpp -o eigen_test -lmkl_rt
works fine with CXX as clang++, g++ and icpx. Setting the environment as shown above is important. In that case -lmkl_rt is plenty. A little bit of adjustment to the code gives you the net benefit in wall clock:
#define EIGEN_USE_BLAS
#define EIGEN_USE_MKL_ALL
#include <iostream>
#include <chrono>
#include <Eigen/Dense>
using namespace Eigen;
using namespace std::chrono;
int main()
{
int n_a_rows = 10000;
int n_a_cols = 10000;
int n_b_rows = n_a_cols;
int n_b_cols = 1000;
MatrixXd a(n_a_rows, n_a_cols);
for (int i = 0; i < n_a_rows; ++ i)
for (int j = 0; j < n_a_cols; ++ j)
a (i, j) = n_a_cols * i + j;
MatrixXd b (n_b_rows, n_b_cols);
for (int i = 0; i < n_b_rows; ++ i)
for (int j = 0; j < n_b_cols; ++ j)
b (i, j) = n_b_cols * i + j;
MatrixXd d (n_a_rows, n_b_cols);
using wall_clock_t = std::chrono::high_resolution_clock;
auto const start = wall_clock_t::now();
clock_t begin = clock();
d = a * b;
clock_t end = clock();
auto const wall = std::chrono::duration<double>(wall_clock_t::now() - start);
double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
std::cout << "CPU time : " << elapsed_secs << std::endl;
std::cout << "Wall time : " << wall.count() << std::endl;
std::cout << "Speed up : " << elapsed_secs/wall.count() << std::endl;
}
The runtime on my 8 core i7-4790K @4GHz shows perfect parallelisation:
With on board blas:
CPU time : 12.5134
Wall time : 1.69036
Speed up : 7.40277
With MKL:
> ./eigen_test
CPU time : 11.4391
Wall time : 1.52542
Speed up : 7.49898
|
70,495,218 | 70,501,225 | How to bind a reference to either a const param or a new object? | Let's say I have this code:
void MyFunc(const std::string& param) {
std::string maybe_altered_param;
if (ConditionIsMet()) {
maybe_altered_param = AlterParam(param);
} else {
maybe_altered_param = param; // <-- unnecessary copy
}
// do stuff with maybe_altered_param
// maybe_altered_param does not need to be modified further.
}
The AlterParam function returns a copy of the string, so when ConditionIsMet returns true, a copy is made in order to populate maybe_altered_param.
However, a copy is made also when ConditionIsMet() returns false, which is suboptimal. In the second case I just want to have another name for the same object, without copies or anything of the sort.
What is the simplest way of removing the unnecessary copy in a case like this?
| With extra variables, you might do:
void MyFunc(const std::string& param) {
std::string maybe_altered_param;
const bool condition_met = ConditionIsMet();
if (condition_met) {
maybe_altered_param = AlterParam(param);
}
const std::string& ref =
condition_met ? maybe_altered_param : param; // both are lvalues, so no copy.
// do stuff with ref
}
|
70,495,253 | 70,565,923 | Is there a way to detect the pixels of a sprite for a collision in SFML? | It doesn't have to be pixel-perfect collision, but I want it to be as close as possible to the actual pixels of the sprite. FYI, I created a 32 by 32 sprite but then I was only able to fill estimately half the amount of pixels, so the rest is just transparent.
| Most games out there don't use anything close to pixel perfect collision and it's usually not needed. Having some approximated rectangle or a combination of multiple rectangles is usually enough.
SFML itself provides intersects() and contains() functions for it's sf::Rect<T> class.
There's also some collision detection class in the SFML wiki which also features a bit-mask collision, that's basically a pixel-perfect collision detection.
|
70,496,043 | 70,496,495 | MISRA warning when overriding bitwise operator | I wrote a simple wrapper for the logging interface, so I can use left-shift operator<< to print log.
logger_wrapper.h
class LoggerWrapper
{
public:
LoggerWrapper(logging::LoggerInterface *logger, logging::LogPriority priority);
~LoggerWrapper();
bool log_enabled();
std::stringstream& get_stream();
private:
std::stringstream stream_;
logging::LoggerInterface *logger_;
logging::LogPriority priority_;
};
template <typename T>
LoggerWrapper& operator<<(LoggerWrapper& record, T&& t) {
if (record.log_enabled())
{
record.get_stream() << std::forward<T>(t);
}
return record;
}
template <typename T>
LoggerWrapper& operator<<(LoggerWrapper&& record, T&& t)
{
return record << std::forward<T>(t);
}
logger_wrapper.cpp
#include "logger_wrapper.h"
LoggerWrapper::LoggerWrapper(logging::LoggerInterface *logger, logging::LogPriority priority)
: logger_{ logger }
, priority_ { priority }
{
}
bool LoggerWrapper::log_enabled()
{
return (nullptr != logger_) && (logger_->isLogPriorityEnable(priority_));
}
std::stringstream& LoggerWrapper::get_stream()
{
return stream_;
}
LoggerWrapper::~LoggerWrapper()
{
if (log_enabled())
{
logger_->log(priority_, stream_.str());
}
}
The code was compiled successfully, but I had some MISRA warning:
M5.17.1 (required): Missing overload for corresponding assignment version of operator (operator<<<basic_string&>())
M5.17.1 (required): Missing overload for corresponding assignment version of operator (operator<<<basic_string<char,char_traits<char>,allocator<char>>>())
M5.17.1 (required): Missing overload for corresponding assignment version of operator (operator<<<const atomic&>())
M5.17.1 (required): Missing overload for corresponding assignment version of operator (operator<<<const basic_string&>())
M5.17.1 (required): Missing overload for corresponding assignment version of operator (operator<<<const char (&)[10]>())
...
According to MISRA C++ 2008, Rule M-5-17-1 states that:
The semantic equivalence between a binary operator and its assignment operator form shall be preserved.
I hope someone can explain me what the warnings mean and what I should do to remove it.
Any reply is greatly appreciated. Thank you.
| The MISRA guideline essentially says that "For any binary operator (call it @), if you overload operator@() for your class then also overload the operator@=(), and ensure they behave consistently". The purpose is to ensure that (where x is an instance of your class).
x = x @ y; // @ may represent +, - , <<, *, /, .....
has the same net effect as (i.e. is consistent with).
x @= y;
In your case, your class has (templated) overloads of operator<<() but no corresponding overloads of operator<<=().
One way to stop the warnings is to provide corresponding overloads of operator<<=() whenever you provide an operator<<() (or vice versa).
For example, provide a operator<<=()
template <typename T>
LoggerWrapper& operator<<=(LoggerWrapper& record, T&& t)
{
if (record.log_enabled())
{
record.get_stream() << std::forward<T>(t);
}
return record;
}
and (to ensure the required consistency), use the approach of defining the operator<<() so it calls the operator<<=().
template <typename T>
LoggerWrapper& operator<<(LoggerWrapper& record, T&& t)
{
return operator<<=(record, t);
}
|
70,497,535 | 70,498,682 | Makefile linking using g++ compiler with CUDA object files | I am trying to compile cuda object files with nvcc, and compile the final main script using the g++ compiler. I have seen this post but wasn't able to get my example working. The error I am getting seems to be a linkage error:
nvcc -c -g -I -dlink -I/usr/local/cuda-11/include -I. -L/usr/local/cuda-11/lib64 -lcudart -lcurand module.cu -o module.o
g++ -I/usr/local/cuda-11/include -I. -L/usr/local/cuda-11/lib64 -lcudart -lcurand module.o main.cpp -o main
module.o: In function `call_kernel()':
/home/ubuntu/Desktop/CUDA/MPI&CUDA/module.cu:16: undefined reference to `__cudaPushCallConfiguration'
module.o: In function `__cudaUnregisterBinaryUtil()':
/usr/local/cuda-11/include/crt/host_runtime.h:259: undefined reference to `__cudaUnregisterFatBinary'
module.o: In function `__nv_init_managed_rt_with_module(void**)':
/usr/local/cuda-11/include/crt/host_runtime.h:264: undefined reference to `__cudaInitModule'
What am I doing wrong ? I am aware I could simply compile main.cpp with nvcc but it is something I don't want, as in my problem, I will replace g++ with mpicxx later and have MPI code inside my main.cpp script.
My makefile is:
INC := -I$(CUDA_HOME)/include -I.
LIB := -L$(CUDA_HOME)/lib64 -lcudart -lcurand
CUDAFLAGS=-c -g -I -dlink $(INC) $(LIB)
all: main
main: module.o
g++ $(INC) $(LIB) module.o main.cpp -o main
module.o: module.cu module.h
nvcc -c -g -I -dlink $(INC) $(LIB) module.cu -o module.o
clean:
rm -rf *.o
main.cpp
#include "module.h"
int main(){
return 0;
}
module.cu
#ifdef __CUDACC__
#define CUDA_GLOBAL __global__
#else
#define CUDA_GLOBAL
#endif
#include <cuda.h>
#include "module.h"
CUDA_GLOBAL
void kernel(){
}
void call_kernel(){
kernel<<<1,1>>>();
}
module.h
#ifndef _MODULE_H_
#define _MODULE_H_
#ifdef __CUDACC__
#define CUDA_GLOBAL __global__
#else
#define CUDA_GLOBAL
#endif
#include <numeric>
#include <cuda.h>
CUDA_GLOBAL
void kernel();
void call_kernel();
#endif
| Your link line is wrong. All libraries (e.g., -lfoo) must come at the end of the link line after all the object files (e.g., .o files).
Not only that, but they need to be ordered properly (but I have no idea what the right order is so maybe they are correct above).
Almost all modern linkers are "single pass" linkers which means that they only go through the libraries one time, and since they only pull symbols in that they already need you must order your libraries with the "highest level" content first, and the "lower level" content following.
|
70,498,030 | 70,498,384 | Template function with template argument parametrized over int | Without using the features of C++11 and higher (I will accept them but would prefer C++98),
I have to write a template function with argument T which is an STL container of ints. It receives such a container along with another int which it tries to search for,
Right now I have this but it doesn't compile:
template <template<int> class T>
T::iterator easyfind(T &container, int val)
{
T::iterator it = container.begin();
for ( ; it != container.end(); it++)
if (val == *it)
break ;
return (it);
}
I wonder if I can somehow force the T parameter to always be a class template that is parametrized over integers... I tried writing T<int> but it still doesn't compile.
| [NOTE] This answer uses C++20. @PatrickRoberts made me notice that you were preferably requesting a C++98 solution. I leave it anyway because it may be of any help to you.
You can just add a requirement for your template, checking the container's type is int.
[Demo]
#include <iostream> // cout
#include <list>
#include <type_traits> // is_same
#include <vector>
template <typename C>
requires std::is_same<typename C::value_type, int>::value
auto easyfind(const C& container, int val)
{
for (auto it{std::cbegin(container)}; it != std::cend(container); ++it)
{
if (val == *it) { return it; }
}
return std::cend(container);
}
int main()
{
std::vector<int> vi{1, 2, 3};
if (auto it{easyfind(vi, 2)}; it != std::cend(vi))
{
std::cout << *it << "\n";
}
std::list<int> li{4, 5, 6};
if (auto it{easyfind(li, 8)}; it != std::cend(li))
{
std::cout << *it << "\n";
}
std::vector<double> vd{0.5, 1.3, 2.8};
//if (auto it{easyfind(vd, 1.3)}; it != std::cend(vd)) // error
//{
// std::cout << *it << "\n";
//}
}
|
70,499,066 | 70,499,069 | Vector push_back returns invalid conversion | Im new to cpp vectors and i keep encountering this issue
error: no matching function for call to ‘push_back(const char [6])’
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<int> names;
names.push_back("Lewis");
names.push_back("Mark");
names.push_back("Reece");
names.push_back("Max");
for(int i = 0; i < names.size(); i++)
cout << names[i] << '\n';
return 0;
}
This is the error
test.cpp: In function ‘int main()’:
test.cpp:6:26: error: no matching function for call to ‘push_back(const char [6])’
6 | names.push_back("Lewis");
| ^
In file included from /usr/include/c++/9/vector:67,
from test.cpp:1:
/usr/include/c++/9/bits/stl_vector.h:1184:7: note: candidate: ‘void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = int; _Alloc = std::allocator<int>; std::vector<_Tp, _Alloc>::value_type = int]’ <near match>
1184 | push_back(const value_type& __x)
| ^~~~~~~~~
/usr/include/c++/9/bits/stl_vector.h:1184:7: note: conversion of argument 1 would be ill-formed:
test.cpp:6:19: error: invalid conversion from ‘const char*’ to ‘std::vector<int>::value_type’ {aka ‘int’} [-fpermissive]
6 | names.push_back("Lewis");
| ^~~~~~~
| |
| const char*
In file included from /usr/include/c++/9/vector:67,
from test.cpp:1:
/usr/include/c++/9/bits/stl_vector.h:1200:7: note: candidate: ‘void std::vector<_Tp, _Alloc>::push_back(std::vector<_Tp, _Alloc>::value_type&&) [with _Tp = int; _Alloc = std::allocator<int>; std::vector<_Tp, _Alloc>::value_type = int]’ <near match>
1200 | push_back(value_type&& __x)
| ^~~~~~~~~
/usr/include/c++/9/bits/stl_vector.h:1200:7: note: conversion of argument 1 would be ill-formed:
test.cpp:6:19: error: invalid conversion from ‘const char*’ to ‘std::vector<int>::value_type’ {aka ‘int’} [-fpermissive]
6 | names.push_back("Lewis");
| ^~~~~~~
| |
| const char*
test.cpp:7:25: error: no matching function for call to ‘push_back(const char [5])’
| The issue is that you are using a vector<int> rather than a vector<string>
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<string> names;
names.push_back("Lewis");
names.push_back("Mark");
names.push_back("Reece");
names.push_back("Max");
for(int i = 0; i < names.size(); i++)
cout << names[i] << '\n';
return 0;
}
|
70,500,480 | 70,501,413 | Asio: how to get async data back into synchronous method | I'm using asio for async io, but there are some times where I'd like to "escape" the async world and get my data back into the regular synchronous world.
For instance, consider that I have a std::deque<string> _data that is being used in my async process (in a single thread always running in the background), and were I've created async function to read / write from it.
What is the "natural" way to read from this deque in a synchronous way from another thread ?
So far I've used atomics to do this but this feels a bit "wrong".
For example:
std::string getDataSync()
{
std::atomic<int> signal = 0;
std::string str;
asio::post(io_context, [this, &signal, &str] {
str = _data.front();
_data.pop_front();
signal = 1;
});
while(signal == 0) { }
return str;
}
Is it ok to do this?
Does asio provide anything cleaner to do this kind of operations?
Thanks
| If you want to synchronize two threads, then you have to use sychronize primitives (like std::atomic). Asio doesn't provide more advanced primitives, but the STL (and boost) is full of it. For your simple example, you might want to use std::future and std::promise to move the top item of the deque to another thread.
Here is a small example. I assume that you don't want to access the deque directly from the other thread, just the top item. I also assume that you are running boost::asio::run in another thread.
inline constexpr std::string pop_from_queue() { return "hello world"; }
int main() {
auto context = boost::asio::io_context{};
auto promise = std::promise<std::string>{};
auto result = promise.get_future();
boost::asio::post(context,
[&promise] { promise.set_value(pop_from_queue()); });
auto thread = std::thread{[&context] { context.run(); }};
std::cout << result.get(); // blocking
thread.join();
}
|
70,500,597 | 70,500,761 | converting hex string to an integer while preserving the format | Title might be aids I don't really know what this process is called. Anyway basically I am using JSON to config my tool. (which is wrote in C++). but I want to configure key binds for GetAsyncKeyState but JSON doesn't support hex which I need for the virtual key codes. A solution for this is to use a string then convert it back to an int. However no method i have found does this properly.
here's some pseudocode for the expected output
string str = "0x01";
int i = 0;
// here i should be converted
std::cout << std::hex << i << std::endl; // this should output 0x01
| unsigned int i = std::stoul(str, nullptr, 16);
|
70,500,657 | 70,500,677 | Is it possible to change a const data value? | can someone explain to me why does this code doesnt change the value of a?
is it possible to change a const data value?
case 1:
const int a = 2;
*((int*)&a) = 3;
std::cout << a;
case 2:
const int a = 2;
const_cast<int&>(a) = 3;
std::cout << a;
| Changing a const value is undefined behavior.
I would advise you not to do it or write any program that does so.
|
70,501,201 | 70,506,860 | How to draw a little square with a pic on it with fltk | i wanna create a board with little squares , and put a picture on every square , how can I do it using fltk on c++ ?
| The recommended method to draw a box with an image in FLTK is to use an Fl_Box widget and assign an image to it which will be used as its label, like:
Fl_Box b(0, 0, 100, 100);
b.image(my_image);
Of course, my_image needs to be a valid image like Fl_Image, Fl_PNG_Image etc.
|
70,501,659 | 70,501,979 | Constructors static keyword use | I read so many definitions of keyword 'static' and I still find it very confusing. Output of this program should be :
1 2 1 2 3 4 1 1 2 3 4 8 7 6 5 1 2 6 5
I understand how global members are called,but when the program reaches the main and static D d; I get all confused. Thank you in advance to anyone willing to explain!
#include <iostream>
using namespace std;
struct D {
D() { cout << "1" << endl; }
~D() { cout << "5" << endl; }
};
class C {
public:
D d;
C() { cout << "2" << endl; }
~C() { cout << "6" << endl; }
};
struct B {
C c;
B() { cout << "3" << endl; }
~B() { cout << "7" << endl; }
};
struct A {
B b;
A() { cout << "4" << endl; }
~A() { cout << "8" << endl; }
};
extern A a;
C c;
int main() {
static D d;
A{};
C{};
return 0;
}
A a;
extern B b;
| For your example, I'm getting
1 2
1 2 3 4
1
1 2 3 4
8 7 6 5
1 2 6 5
5 8 7 6 5 6 5
I broke the output down in groups that correspond to paragraphs that follow.
First, the global variable C c; is constructed. This first constructs its member variable of type D, which prints 1; then C's constructor prints 2. That's the first 1 2 accounted for.
Then, the global variable A a; is constructed. Even though the definition is after main, global variables are constructed before main is entered. This first constructs the member of type B, which in turn constructs a member of type C, which we already know prints 1 2. Then B's constructor prints 3 and finally A's constructor prints 4. This is the next 1 2 3 4 accounted for.
Then main runs, and it first constructs static D d;, which prints 1.
Then the temporary A{} is constructed, which we already know prints 1 2 3 4. Then this temporary is destroyed. Destructors always run in the reverse order of construction, hence 8 7 6 5
Then the temporary C{} is constructed and immediately destroyed. We already know C's construction prints 1 2, and destruction prints 6 5.
And finally, main exits, and the static D d and the two global variables are destroyed in the reverse order of construction. They printed 1 2 1 2 3 4 1 on the way up, so they now print 5 8 7 6 5 6 5 on the way down.
In this example, nothing will change if static keyword is removed from static D d;. In main function specifically, static local variables are rather pointless.
|
70,502,206 | 70,502,334 | Checking for a match in each element of a 2d vector | I'm creating text based TicTacToe in C++ and need to create a function that checks for a win.
Right now, I have a vector of all the moves player X has made:
std::vector<int> x_vector = {1, 2, 3, 5, 7};
I also have a 2d vector of win conditions:
std::vector<std::vector> > wins = {{1, 2, 3}, {4, 5, 6}, {7, 8, 8}};
In this case, each element of the wins vector represents a win condition. If player X ever has a combination of inputs in their vector that includes one of the win conditions, I'm trying to get a bool function to return true.
I'm new to C++ and coding in general, so all patience is appreciated, and the simpler the solution you can help me find the better.
| You can iterate through your list of known wins, checking each to see if it is a subset of the list of user's moves. The std::includes function will do this test – but note that the two 'lists' need to be sorted.
To avoid having to manually sort the list of user's moves after each input, you can use the std::set container (which is inherently sorted), instead of std::vector.
The following snippet shows a relatively simple implementation of an isWin() function using this approach, along with some rudimentary test cases:
#include <iostream>
#include <vector>
#include <set>
#include <algorithm> // For std::includes
bool isWin(const std::set<int>& test)
{
static std::vector<std::set<int>> winlist = {
{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, // Horizontal lines
{1, 4, 7}, {2, 5, 8}, {3, 6, 9}, // Vertical lines
{1, 5, 9}, {3, 5, 7}, // Diagonal lines
};
for (auto win : winlist) {
if (std::includes(test.begin(), test.end(), win.begin(), win.end())) {
return true; // Match - Win!
}
}
return false; // Didn't get a match - no win
}
int main()
{
std::set<int> s1{ 1, 2 }; // Trivial "No win" (only 2 moves)
std::cout << "s1: " << isWin(s1) << "\n";
std::set<int> s2{ 1, 2, 3 }; // Trivial "Win" (top row)
std::cout << "s2: " << isWin(s2) << "\n";
std::set<int> s3{ 2, 4, 1, 5 }; // " No Win"
std::cout << "s3: " << isWin(s3) << "\n";
std::set<int> s4{ 5, 2, 4, 6 }; // "Win" (middle row)
std::cout << "s4: " << isWin(s4) << "\n";
std::set<int> s5{ 5, 1, 3, 6, 9 }; // "Win" (diagonal)
std::cout << "s5: " << isWin(s5) << "\n";
return 0;
}
Note that this approach may not be the best for checking wins in a Tic-Tac-Toe game; however, if your purpose is to learn about vectors, sets and looking for matching sub-sequences, it may provide a useful starting-point.
For your actual user input, you would declare and initialize an empty set and then add moves using the insert member function of the std::set container class; something like this:
int main()
{
std::set<int> user{}; // Empty Set
user.insert(5);
user.insert(2);
user.insert(4);
user.insert(6);
std::cout << "user (1): " << isWin(user) << "\n";
user.clear();
user.insert(2);
user.insert(4);
user.insert(1);
user.insert(5);
std::cout << "user (2): " << isWin(user) << "\n";
return 0;
}
|
70,502,500 | 70,565,778 | What's the difference between getLocalBounds and getGlobalBounds in sfml c++? | I was making a collision detection for my objects, and was just wondering why I should use GlobalBounds instead of LocalBounds? or does it not matter which function I use?
| In simple terms: global bounds = local bounds + transformations and since you most of the time want to deal with the transformed position, scale or rotation, the global bounds become more useful than the local ones.
Of course there are always use cases, where local bounds can be useful.
|
70,502,661 | 70,503,168 | Fill Matrix in Spiral Form from center | I recently finished making an algorithm for a project I'm working on.
Briefly, a part of my project needs to fill a matrix, the requirements of how to do it are these:
- Fill the matrix in form of spiral, from the center.
- The size of the matrix must be dynamic, so the spiral can be large or small.
- Every two times a cell of the matrix is filled, //DO STUFF must be executed.
In the end, the code that I made works, it was my best effort and I am not able to optimize it more, it bothers me a bit having had to use so many ifs, and I was wondering if someone could take a look at my code to see if it is possible to optimize it further or some constructive comment (it works well, but it would be great if it was faster, since this algorithm will be executed several times in my project). Also so that other people can use it!
#include <stdio.h>
typedef unsigned short u16_t;
const u16_t size = 7; //<-- CHANGE HERE!!! just odd numbers and bigger than 3
const u16_t maxTimes = 2;
u16_t array_cont[size][size] = { 0 };
u16_t counter = 3, curr = 0;
u16_t endColumn = (size - 1) / 2, endRow = endColumn;
u16_t startColumn = endColumn + 1, startRow = endColumn + 1;
u16_t posLoop = 2, buffer = startColumn, i = 0;
void fillArray() {
if (curr < maxTimes) {
if (posLoop == 0) { //Top
for (i = buffer; i <= startColumn && curr < maxTimes; i++, curr++)
array_cont[endRow][i] = counter++;
if (curr == maxTimes) {
if (i <= startColumn) {
buffer = i;
} else {
buffer = endRow;
startColumn++;
posLoop++;
}
} else {
buffer = endRow;
startColumn++;
posLoop++;
fillArray();
}
} else if (posLoop == 1) { //Right
for (i = buffer; i <= startRow && curr < maxTimes; i++, curr++)
array_cont[i][startColumn] = counter++;
if (curr == maxTimes) {
if (i <= startRow) {
buffer = i;
} else {
buffer = startColumn;
startRow++;
posLoop++;
}
} else {
buffer = startColumn;
startRow++;
posLoop++;
fillArray();
}
} else if (posLoop == 2) { //Bottom
for (i = buffer; i >= endColumn && curr < maxTimes; i--, curr++)
array_cont[startRow][i] = counter++;
if (curr == maxTimes) {
if (i >= endColumn) {
buffer = i;
} else {
buffer = startRow;
endColumn--;
posLoop++;
}
} else {
buffer = startRow;
endColumn--;
posLoop++;
fillArray();
}
} else if (posLoop == 3) { //Left
for (i = buffer; i >= endRow && curr < maxTimes; i--, curr++)
array_cont[i][endColumn] = counter++;
if (curr == maxTimes) {
if (i >= endRow) {
buffer = i;
} else {
buffer = endColumn;
endRow--;
posLoop = 0;
}
} else {
buffer = endColumn;
endRow--;
posLoop = 0;
fillArray();
}
}
}
}
int main(void) {
array_cont[endColumn][endColumn] = 1;
array_cont[endColumn][endColumn + 1] = 2;
//DO STUFF
u16_t max = ((size * size) - 1) / maxTimes;
for (u16_t j = 0; j < max; j++) {
fillArray();
curr = 0;
//DO STUFF
}
//Demostration
for (u16_t x = 0; x < size; x++) {
for (u16_t y = 0; y < size; y++)
printf("%-4d ", array_cont[x][y]);
printf("\n");
}
return 0;
}
|
Notice that the numbers along the diagonal (1, 9, 25, 49) are the squares of the odd numbers. That's an important clue, since it suggests that the 1 in the center of the matrix should be treated as the end of a spiral.
From the end of each spiral, the x,y coordinates should be adjusted up and to the right by 1. Then the next layer of the spiral can be constructed by moving down, left, up, and right by the same amount.
For example, starting from the position of the 1, move up and to the right (to the position of the 9), and then form a loop with the following procedure:
move down, and place the 2
move down, and place the 3
move left, and place the 4
move left, and place the 5
etc.
Thus the code looks something like this:
int size = 7;
int matrix[size][size];
int dy[] = { 1, 0, -1, 0 };
int dx[] = { 0, -1, 0, 1 };
int directionCount = 4;
int ringCount = (size - 1) / 2;
int y = ringCount;
int x = ringCount;
int repeatCount = 0;
int value = 1;
matrix[y][x] = value++;
for (int ring = 0; ring < ringCount; ring++)
{
y--;
x++;
repeatCount += 2;
for (int direction = 0; direction < directionCount; direction++)
for (int repeat = 0; repeat < repeatCount; repeat++)
{
y += dy[direction];
x += dx[direction];
matrix[y][x] = value++;
}
}
|
70,502,897 | 70,503,042 | any reason not to use 'protected' in this situation (cpp, c++, oop) | #include <iostream>
using namespace std;
class R {
protected:
int a;
public:
int read(void) {
return a;
}
};
class RW : public R {
public:
void write(int _a) {
a = _a;
}
};
int main(void) {
int a;
R *r = (R *)&a;
RW *rw = (RW *)&a;
rw->write(1);
cout << dec << r->read() << endl;
cout << dec << rw->read() << endl;
return 0;
}
I want to make a class that can only read (class R) and a class can read and write (class RW). Is there any reason I should not do this in oop? and also any reason not to use the 'protected' here?
Please help me, thanks for any replies!
P.S. I don't want to define duplicated 'private int a;' on both classes, because the offset of 'int a in class RW' and size of 'class RW' is not the same to the 'class R' anymore.
|
any reason not to use the 'protected' here?
protected member variables are sometimes discouraged in favor of protected member functions that accesses private member variables - and you don't need duplicate as if you make it private in R. You could add a protected member function to write to it instead.
class R {
public:
int read() const { // not `void` and add `const`
return a;
}
protected:
void write(int A) {
a = A;
}
private:
int a;
};
class RW : public R {
public:
void write(int A) {
R::write(A);
}
};
Without any added validation in R::write, the above basically does the same as your code, but a is private.
Your original version is not wrong though. As can be seen here: Should you ever use protected member variables? there's no definite "no, you should never use protected member variables".
One may argue that if they are only protected, one can just inherit the class and treat them as public and if changing such member variables doesn't require any validation of any sort, they could be made public to start with. One would have to look at it from case to case.
|
70,502,973 | 70,503,028 | Extra output when writing to file using std::cout | I am trying to read data from a file in.txt, and after some computations, I am writing the output to out.txt
Why is there an extra 7 at the end of out.txt?
Contents of Solution class.
class Solution
{
public:
int findComplement(int num)
{
int powerof2 = 2, temp = num;
/*
get number of bits corresponding to the number, and
find the smallest power of 2 greater than the number.
*/
while (temp >> 1)
{
temp >>= 1;
powerof2 <<= 1;
}
// subtract the number from powerof2 -1
return powerof2 - 1 - num;
}
};
Contents of main function.
Assume all headers are included. findComplement flips bits of a number. For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2.
int main() {
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
// helper variables
Solution answer;
int testcase;
// read input file, compute answer, and write to output file
while (std::cin) {
std::cin >> testcase;
std::cout << answer.findComplement(testcase) << "\n";
}
return 0;
}
Contents of in.txt
5
1
1000
120
Contents of out.txt
2
0
23
7
7
| The reason there is an extra 7 is that your loop executes one too many times. You need to check std::cin after you've tried to read the input.
As is, you simply repeat the last test case.
|
70,503,103 | 70,503,278 | How to choose MPI vendor/distribution with CMake? | I have a program that I would like to compile with CMake + make but using two different MPI distributions, OpenMPI and MPICH.
In Ubuntu, I have both installed; these are all the compiler wrappers I have installed:
mpic++ mpicxx mpif77.mpich mpijavac
mpicc mpicxx.mpich mpif77.openmpi mpijavac.pl
mpiCC mpicxx.openmpi mpif90 mpirun
mpicc.mpich mpiexec mpif90.mpich mpirun.mpich
mpicc.openmpi mpiexec.hydra mpif90.openmpi mpirun.openmpi
mpiCC.openmpi mpiexec.mpich mpifort mpivars
mpichversion mpiexec.openmpi mpifort.mpich
mpic++.openmpi mpif77 mpifort.openmpi
(OpenMPI is the default, i.e. when no distribution extension is specified. I am not using modules.)
How can I force CMake to choose MPICH over OpenMPI?
I tried setting -DMPI_ROOT=/usr/lib/x86_64-linux-gnu/mpich but
I get this error:
-- Could NOT find MPI_CXX (missing: MPI_CXX_WORKS)
CMake Error at /usr/share/cmake-3.18/Modules/FindPackageHandleStandardArgs.cmake:165 (message):
Could NOT find MPI (missing: MPI_CXX_FOUND)
Reason given by package: MPI component 'C' was requested, but language C is not enabled. MPI component 'Fortran' was requested, but language Fortran is not enabled.
Call Stack (most recent call first):
/usr/share/cmake-3.18/Modules/FindPackageHandleStandardArgs.cmake:458 (_FPHSA_FAILURE_MESSAGE)
/usr/share/cmake-3.18/Modules/FindMPI.cmake:1721 (find_package_handle_standard_args)
CMakeLists.txt:11 (find_package)
it still uses OpenMPI.
This is how my CMakeLists.txt looks like:
cmake_minimum_required(VERSION 3.12.0)
project(myproject VERSION 0.1 LANGUAGES CXX)
#enable_language(C) #uncommenting these doesn't help
#enable_language(Fortran)
enable_testing()
include(CTest)
find_package(MPI REQUIRED)
| Setting -DMPI_ROOT= or -DMPI_HOME= didn't work for me. It still uses the default in my system (OpenMPI).
What worked was to set -DMPI_EXECUTABLE_SUFFIX=.mpich, option which I found near the end of the documentation: https://cmake.org/cmake/help/latest/module/FindMPI.html.
|
70,503,267 | 70,503,383 | Is there a way to use bools with strings? I want to search for a word in a string, and if it's there, output the meaning | I am very new to coding and this is my first language, C++. I have an assignment that is really confusing.
The assignment wants me to search the user input of one line for slang words. Ex: TMI or BFF. However, I don't know how to use conditional expressions to do this, and I have tried if-else statements but they end up reading all the statements instead of each one that applies. The code always comes up with a problem for the conditional expression because I honestly have no clue how to use them for strings in this manner. Any help is appreciated!
(Slang terms are required to be capitalized to be read.)
#include <iostream>
#include <cctype>
#include <iomanip>
#include <string>
using namespace std;
int main() {
string userInput;
int textSlang = '0';
cout << "Welcome to the Text Message Decoder!" << endl;
cout << "WARNING! Slang is case-sensitive. Please make sure all slang is fully capitalized!" << endl;
cout << "Enter a single line text message: " << endl;
getline(cin, userInput);
cout << "You entered: " << userInput << endl;
if (textSlang == string::npos) {
cout << "Error" << endl;
}
else if ((textSlang = userInput.find("IDK" ))) {
cout << "IDK: I don't know" << endl;
}
else if ((textSlang = userInput.find("TTYL" ))) {
cout << "TTYL: Talk to you later" << endl;
}
else if ((textSlang = userInput.find("TMI" ))) {
cout << "TMI: Too much information" << endl;
}
else if ((textSlang = userInput.find("JK" ))) {
cout << "JK: Just kidding" << endl;
}
else if ((textSlang = userInput.find("BFF" ))) {
cout << "BFF: Best friends forever" << endl;
}
else if ((textSlang = userInput.find("LOL" ))) {
cout << "LOL: Laugh out loud" << endl;
}
else if ((textSlang = userInput.find("TYSM" ))) {
cout << "TYSM: Thank you so much" << endl;
}
else if ((textSlang = userInput.find("OMG" ))) {
cout << "OMG: Oh my god" << endl;
}
cout << "END." << endl;
//textSlang = userInput.find("TTYL");
//textSlang = userInput.find("TMI");
//textSlang = userInput.find("JK");
//textSlang = userInput.find("BFF");
//textSlang = userInput.find("LOL");
//textSlang = userInput.find("TYSM");
//textSlang = userInput.find("OMG");
}
| This code:
else if ((textSlang = userInput.find("IDK" ))) {
cout << "IDK: I don't know" << endl;
}
assigns textSlang to 0 IFF userInput begins with IDK. In all other cases it assigns some value other than 0.
And all int values other that 0 evaluate to true.
You want:
else if ((textSlang = userInput.find("IDK" )) != string::npos) {
cout << "IDK: I don't know" << endl;
}
|
70,503,372 | 70,503,917 | No member named "XXX" in a simple CRTP case | Here I have a simple CRTP case:
#include <cstddef>
#include <utility>
template <typename Impl>
class base
{
constexpr static size_t impl_num = Impl::num;
};
template <typename Impl>
class deriv : public base<deriv<Impl>>
{
friend class base<deriv<Impl>>;
constexpr static size_t num = Impl::num_in;
};
class actual_impl
{
public:
constexpr static size_t num_in = 10;
};
using my_type = deriv<actual_impl>;
int main()
{
my_type a{};
}
This snippet compiles fine but when I change the base class to:
#include <cstddef>
#include <utility>
template <typename Impl>
class base
{
constexpr static std::make_index_sequence<Impl::num> idx{};
};
template <typename Impl>
class deriv : public base<deriv<Impl>>
{
friend class base<deriv<Impl>>;
constexpr static size_t num = Impl::num_in;
};
class actual_impl
{
public:
constexpr static size_t num_in = 10;
};
using my_type = deriv<actual_impl>;
int main()
{
my_type a{};
}
Clang complains that error: no member named 'num' in 'deriv<actual_impl>'. I'm just confused why the first case works but not the second one, what's the fundamental difference between these two since it seems to me that in both cases Impl::num_in are used in base class.
In general, is it possible for base class to use typedefs or constexprs from Impl?
| The fundamental difference is the moment when you're trying to access the internals of the Impl class. Impl in base<Impl> is an incomplete type, and there are certain restrictions on what you can do with it.
In particular, you can't access num data member inside base, that's why the line
constexpr static std::make_index_sequence<Impl::num> idx{};
causes a compilation error. Note that to define the base class, a compiler has to know the value of Impl::num right at that moment.
In contrast to that, in your first example, Impl::num is used only to initialize a value of impl_num, which otherwise doesn't depend on Impl::num. Instantiation of that initialization happen later, at the point when Impl becomes a complete type. Hence, there is no error.
If you slightly change the definition,
template<typename Impl>
class base {
constexpr static decltype(Impl::num) impl_num = Impl::num;
// or
constexpr static auto impl_num = Impl::num;
}
and make impl_num type dependent on Impl, you'll get the same error by the same reason.
Adding indirection doesn't help, the following code also fails to compile:
template<typename Impl>
class base {
constexpr static size_t impl_num = Impl::num;
constexpr static std::make_index_sequence<impl_num> idx{};
};
In general, is it possible for base class to use typedefs or constexprs from Impl?
It depends. You can use them only in contexts where instantiations happen when Impl is a complete type. For example,
template<typename Impl>
class base {
public:
void foo() {
decltype(Impl::num) impl_num = 0;
}
};
is fine, but
template<typename Impl>
class base {
public:
decltype(Impl::num) foo() {
return 0;
}
};
is not.
The standard trick to avoid potential problems with incomplete types in CRTP is the introduction of a helper traits class:
// Just forward declarations
template<typename Impl> class deriv;
class actual_impl;
using my_type = deriv<actual_impl>;
template<class> struct traits;
template<> struct traits<my_type> {
using num_type = std::size_t;
};
template <typename Impl>
class base {
public:
typename traits<Impl>::num_type foo() {
return 0;
}
};
// Now actual definitions
// ...
Here, to access traits<Impl> internals, Impl doesn't have to be a complete type.
|
70,503,521 | 70,503,604 | Linking to lib on Linux without headers | Hello I'm trying to link to a library without headers. I wrote prototype exactly as defined in library, but ld cannot link it.
readelf -Ws Release/libcef.so | grep KeyStringToDomKey
386822: 00000000066d73d0 328 FUNC LOCAL HIDDEN 17 _ZN2ui16KeycodeConverter17KeyStringToDomKeyERKNSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEE
readelf -Ws main-6cf4e2.o | grep KeyStringToDomKey
13: 0000000000000000 0 NOTYPE GLOBAL DEFAULT UND _ZN2ui16KeycodeConverter17KeyStringToDomKeyERKNSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEE
#include <iostream>
#include <string>
#include "domkey.h"
namespace ui {
class KeycodeConverter {
public:
static DomKey KeyStringToDomKey(const std::string&);
};
}
using namespace std;
int main()
{
auto t = ui::KeycodeConverter::KeyStringToDomKey("t");
cout << "Hello World!" << endl;
return 0;
}
|
386822: 00000000066d73d0 328 FUNC LOCAL HIDDEN 17 _ZN2u...
HIDDEN is the key here: this symbol is not visible outside of the shared library (neither to static linker /usr/bin/ld, nor to the dynamic loader).
|
70,503,703 | 70,503,760 | C++11 : Using local static variables in multithreaded program caused coredump | In C++11, I create 100 threads, every thread call Test::PushFunc, add local static variable index, insert to a local set variable localMap.
In theory, index is stored in Initialized Data Segment Memory and was added by every thread in program running time.
Following line
assert(it == localMap.end());
is reasonable because of index to be inserted into localMap is never repeated.
But in practice, program is coredump in assert randomly. Can U tell me why ? Thanks.
#include <set>
#include <iostream>
#include <thread>
class Test {
public:
std::set<std::string> localMap;
void PushFunc()
{
static uint64_t index = 0;
while (true) {
std::cout << "index : " << index << "\n";
++index;
const auto& s = std::to_string(index);
const auto& it = localMap.find(s);
assert(it == localMap.end()); //! coredump here
localMap.insert(s);
if (index > 20000000) {
break;
}
}
}
};
int main ()
{
std::vector<std::thread> processThreads;
for (int i = 0; i < 100; ++i) {
processThreads.emplace_back(
std::thread([]()
{
Test t;
t.PushFunc();
}
));
}
for(auto& thread : processThreads){
thread.join();
}
}
|
But in practice, program is coredump in assert randomly. Can U tell me why ?
Because you have a data race -- multiple threads are trying to read and write the same variable without any synchronization.
The index is a global variable. You need to guard access to it with a mutex.
Udate:
But localMap is not a global variable, data race cannot explain one index repeated twice.
A program with a data race (undefined behavior) can produce any result.
Yes, it can.
Consider the following instruction interleaving (time goes downwards):
T1 loads index into register (say 5).
T2 loads index (5 again)
T1 increments index to 6, stores "6" into its map
T1 loads 6, increments index to 7, stores "7" into its map
T2 "increments" index to 6, stores "6" into its own map
T1 loads 6, increments it to 7, tries to store "7" into its map ==> assertion failure!
The issue is that index++ is not an atomic operation, and (without mutex) other threads may interfere with it.
|
70,503,725 | 70,504,139 | std::erase_if delete an extra elements on std::vector? | I use std::erase_if to erase half the elements from containers using a captured counter as follows. C++20 compiled with gcc10
#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
int main()
{
{
std::vector<int> container(10);
std::cout << container.size() << std::endl;
std::erase_if(container, [i = 0u](auto&&...) mutable { return i++ % 2 == 0; });
std::cout << container.size() << std::endl;
}
std::cout << std::endl;
{
std::map<int, int> container;
for (int i = 0; i < 10; i++) {
container.emplace(i, i);
}
std::cout << container.size() << std::endl;
std::erase_if(container, [i = 0u](auto&&...) mutable { return i++ % 2 == 0; });
std::cout << container.size() << std::endl;
}
std::cout << std::endl;
{
std::unordered_map<int, int> container;
for (int i = 0; i < 10; i++) {
container.emplace(i, i);
}
std::cout << container.size() << std::endl;
std::erase_if(container, [i = 0u](auto&&...) mutable { return i++ % 2 == 0; });
std::cout << container.size() << std::endl;
}
}
The output is unexpected. For vector, an extra element is removed:
10
4
10
5
10
5
I print out the result and it seems like vector[1] is the unexpectedly removed element
Granted that this is not usually a normal usage for erase_if but I'm still curious why it happens only for vector but not for the other map. I'd guess it has something to do with the iterator type shenanigan. Appreciate if someone could give a detailed explanation.
| remove_if takes a Predicate. And the standard library requires that a Predicate type:
Given a glvalue u of type (possibly const) T that designates the same object as *first, pred(u) shall be a valid expression that is equal to pred(*first).
Your predicate changes its internal state. As such, calling it twice with the same element will yield different results. That means it does not fulfill the requirements of Predicate.
And therefore, undefined behavior ensues.
|
70,504,125 | 70,504,313 | pybind11 py::class_.def_property_readonly_static incompatible function arguments for () -> str | I'm trying to bind C++ class static non-arguments method to python class static constant field use pybind11.
Here's my sample code config.cpp:
namespace py = pybind11;
struct Env {
static std::string env() {
return std::getenv("MY_ENV");
}
};
PYBIND11_MODULE(config, m) {
m.doc() = "my config module written in C++";
py::class_<Env>(m, "Env")
.def_property_readonly_static("ENV", &Env::env);
}
The config module compiles successfully, but when I use it in python3 console, here's the exception it raise:
>>> from config import Env
>>> Env.ENV
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: (): incompatible function arguments. The following argument types are supported:
1. () -> str
Invoked with: <class 'config.Env'>
How should I fix this ?
Or is there a way to bind C++ function to python module constant attributes/variables ?
| Here's the answer about how to bind C++ class static non-arguments method to python class static constant attribute/variable with def_property_readonly_static API: https://pybind11.readthedocs.io/en/stable/advanced/classes.html#static-properties
The key is to use C++11 lambda, so update PYBIND11_MODULE part in config.cpp like this:
PYBIND11_MODULE(config, m) {
m.doc() = "my config module written in C++";
py::class_<Env>(m, "Env")
.def_property_readonly_static("ENV", [](py::object /* self */){ return Env::env(); });
}
For the second question, how to bind C++ non-arguments function to python constant attributes/variables, I still have no idea.
|
70,505,162 | 70,505,238 | Why would one want to put a unary plus (+) operator in front of a C++ lambda? | I found out that in C++ we can use + in lambda function +[]{}
Example from the article:
#include <iostream>
#include <type_traits>
int main()
{
auto funcPtr = +[] {};
static_assert(std::is_same<decltype(funcPtr), void (*)()>::value);
}
The main idea of + sign in lambda
You can force the compiler to generate lambda as a function pointer rather than closure by adding + in front of it as above.
But what are advantages of using '+' in lambda? Could you please provide example or link me to the explanation?
| It's not a feature of lambda and more is a feature of implicit type conversion.
What happens there is stemming from the fact that a captureless lambda can be implicitly converted to a pointer to function with same signature as lambda's operator(). +[]{} is an expression where unary + is a no-op , so the only legal result of expression is a pointer to function.
In result auto funcPtr would be a pointer to a function, not an instance of an object with anonymous type returned by lambda expression. Not much of advantage in provided code, but it can be important in type-agnostic code, e.g. where some kind of decltype expression is used. E.g.
#include <type_traits>
void foo(int);
template<class T>
struct is_foo : std::is_same<T, decltype(&foo)> {};
int main()
{
auto foo1 = +[](int)->void {};
auto foo2 = [](int)->void {};
static_assert(is_foo<decltype(foo1)>::value, "foo1 is not like foo");
static_assert(is_foo<decltype(+foo2)>::value, "+foo2 is not like foo");
static_assert(is_foo<decltype(foo2)>::value, "foo2 is not like foo");
}
Note that you can do same with foo: std::is_same<T, decltype(+foo)> {};
Albeit some platforms may not support that, because they inherently may have a variety of function pointers with different calling convention and the expression will be ambiguous.
|
70,505,765 | 70,509,655 | std::allocator deallocate don't use size argument | I'm learn about std::allocator. I try to allocate but use deallocate incorrectly I saw that it didn't use size argument, I confuse about the method could you please explain for me ? Thanks.
testcase1 "test" : I didn't deallocate, valgrind detected (correct)
testcase2 "test_deallocate" : I deallocate with size(0) less than actual size (400),valgrind or -fsanitize=address can't detect leak
testcase3 "test_deallocate2": I deallocate with size(10000) greater than actual size (400) compiler didn't warning , g++ with -fsanitize=address also can't detect this.
#include <iostream>
#include <memory>
using namespace std;
void test(){
allocator<int> al;
int* bl = al.allocate(100);
}
void test_deallocate(){
allocator<int> al;
int* bl = al.allocate(100);
al.deallocate(bl, 0);
}
void test_deallocate2(){
allocator<int> al;
int* bl = al.allocate(100);
al.deallocate(bl, 10000);
}
int main(){
test();
test_deallocate();
test_deallocate2();
return 0;
}
Valgrind:
valgrind --leak-check=full ./a.out
==12655== Memcheck, a memory error detector
==12655== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==12655== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==12655== Command: ./a.out
==12655==
==12655==
==12655== HEAP SUMMARY:
==12655== in use at exit: 400 bytes in 1 blocks
==12655== total heap usage: 4 allocs, 3 frees, 73,904 bytes allocated
==12655==
==12655== 400 bytes in 1 blocks are definitely lost in loss record 1 of 1
==12655== at 0x483BE63: operator new(unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==12655== by 0x1090D1: allocate (new_allocator.h:114)
==12655== by 0x1090D1: test (test.cpp:8)
==12655== by 0x1090D1: main (test.cpp:27)
==12655==
==12655== LEAK SUMMARY:
==12655== definitely lost: 400 bytes in 1 blocks
==12655== indirectly lost: 0 bytes in 0 blocks
==12655== possibly lost: 0 bytes in 0 blocks
==12655== still reachable: 0 bytes in 0 blocks
==12655== suppressed: 0 bytes in 0 blocks
==12655==
==12655== For lists of detected and suppressed errors, rerun with: -s
==12655== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
| Valgrind only intercepts the lower level allocation functions (malloc, new etc.). So it all depends on what the implementation of allocate and deallocate do.
Currently Valgrind doesn't do much checking of sized delete (or aligned new for that matter, see why does std::allocator::deallocate require a size? and https://bugs.kde.org/show_bug.cgi?id=433859).
I may implement something for these in 2022.
If you use GCC libstdc++ or clang libc++ then their sized deletes do not do anything special, they just call plain delete. I haven't looked for deallocate.
|
70,505,843 | 70,546,672 | Android Studio NDK app performance difference between RUN and BUILD | I am trying to create a sudoku app with C++, SDL2 and Android Studio NDK.
In theory it is already working well unless I build and install the app manually.
While I get around 50-60 FPS when I run the app with the RUN-Button in Android Studio, there is a major performance drop when I install the app via BUILD -> GENERATE SIGNED BUNDLE / APK... -> APK and put it on the SD-Card on an actual android device (I've testet this on Xiaomi Mi A1, Samsung Tab S3 and some older devices). I get around 9-11 FPS when installing the app manually.
To create the project, I used the template project in the SDL2 package (version 2.0.18).
I use the same (release-)Build Variant for both cases.
The app is build via NDK-Build.
My conclusion is, that while my code for rendering is maybe not the most efficient, it is not the problem which causes this massive performance issue here.
Screenshot: build with RUN Screenshot: build with BUILD -> GENERATE SIGNED BUNDLE / APK... -> APK
I already tried change several build settings, including switching between debug and release mode, adding optimization (C and C++ -)flags in the Application.mk file, build with uncompressed assets. The performance stays the same in both cases.
My Question is: What could be the difference between building the APK and clicking on RUN, which causes this performance issue?
I hope someone can help me out here, because I am very clueless at the moment. Thank you in advance.
| The difference between RUN and BUILD is in my Run-configuration.
Under Installation Options -> Deploy I chose "APK from app bundle". After researching and trying for hours I changed it to "Default APK", which caused the same performance problems as building and manual install as described in my question above.
While I still don't really know why this is the case, I found a way to get an APK-file which, at least for now, works for me:
Instead of building with BUILD -> GENERATE SIGNED BUNDLE / APK... -> APK I now choose BUILD -> GENERATE SIGNED BUNDLE / APK... -> ANDROID APP BUNDLE and convert the app bundle to an APK via bundletool (https://developer.android.com/studio/command-line/bundletool). The converted APK runs fine on my android device.
|
70,506,148 | 70,506,620 | Multi Monitor Selecting | I want to use multi monitors. Like when application started , I will see all monitors and click one of them ,then application will start the monitor that I selected. How can I do this?
| Call EnumDisplayDevices to enumerate display adapters and monitors. Call ChangeDisplaySettings to move and/or turn monitors on/off.
Call MonitorFromPoint and GetMonitorInfo to find the work area for application windows.
|
70,506,156 | 70,517,564 | Embedded Linux, Qt4 QPrinter: PDF file content is bold and ugly | I am creating a PDF file using QPrinter in Qt4.8,
QPrinter printer(QPrinter::HighResolution);
QTextDocument document;
document.setHtml(html);
printer.setOrientation(QPrinter::Landscape);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setPaperSize(QPrinter::A4);
printer.setOutputFileName(fName);
// printer.setFullPage(true);
// printer.setMargins({ 20, 20, 20, 20});
// printer.setPageMargins(QMarginsF(10, 10, 10, 10));
document.documentLayout()->setPaintDevice(&printer);
document.setPageSize(printer.pageRect().size());
document.print(&printer);
But the result is very ugly text as in this image (rectangle in the below):
What is interesting is that following this answer, at some point I could get a very clear text as in the top rectangle in the image. But during refactoring something seems to be changed and I cannot get clear PDF files anymore. I tried every possible ways I know. No result. Could you help me?
BTW, in the Ubuntu laptop a PDF file is fine, but in the target device (Embedded Linux) the resulted PDF is not clear.
PS: I forgot to commit the working code, therefore this problem.
| It seems the problem is not about QPrinter at all. When refactoring I changed html contents of QTextDocument and unsupported CSS was causing the problem. I changed this:
body {
font-family: "Helvetica, Arial, sans-serif"; // quotes are not supported
font-style: normal;
font-size: 12px;
}
table.bordered , .bordered th, .bordered td {
text-align: center; // this is not supported also
border-width: 1px;
border-collapse: collapse;
font-weight: normal;
}
To this:
table.bordered, .bordered th, .bordered td {
border-width: 1px;
border-collapse: collapse;
font-weight: normal;
font-family: Arial, sans-serif;
font-size: 12px;
}
Now it is working.
|
70,506,485 | 70,515,900 | In Qt6 cin/getline does not read any input for me | I am just starting with QT6 (and with QT in general).
I have tried to do simpe cin/cout operations and it's already troublesome.
Somehow cin does not read a line, nor does getline.
Here is my code:
#include <QCoreApplication>
#include <iostream>
#include <string>
using namespace std;
void do_something()
{
string name = "";
cout << "Enter your name: \n";
cin >> name;
cout << "Hello " << name << "\n";
return;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
do_something();
return a.exec();
}
The line "Enter your name: " get's written, the newline character does not!?
Then whatever i type in the console, does not do anything to cin, and the program is, as it seems stuck in cin.
If instead of "\n" i use "endl" for the "\n" at the second cout, the following happens.
Cin is completely getting ignored and the "Hello" also gets printed.
| The solution was, as written in the comments:
Run the program in the Terminal, not in the QT Creator's Output Termina.
In the output Terminal you cannot type any input.
Flush the buffer because the text lies in the buffer until a endl or a flush occurs.
|
70,506,714 | 70,506,752 | C++ pointer member initialization | I know this is really basic, but I don't know the answer given my very limited C++ usage.
I was told whenever a class contains a pointer as a member, I should allocate memory for it. (and then use 'delete' inside the destructor to free the space)
class Person{
public:
string* ptr_name;
Person(string& name){
ptr_name = new string(name);
}
...
}
I was thinking if I can just do this instead
class Person{
public:
string* ptr_name;
Person(string name){
ptr_name = &name;
}
...
}
As I didn't use '&' inside the constructor argument, 'name' is copied by value inside the constructor. So memory is already allocated for it. The explicit destructor will be unnecessary since the pointer will be automatically destroyed on stack.
Would this work?
| After calling this constructor
Person(string name){
ptr_name = &name;
}
the pointer ptr_name will be invalid because the local variable name will be destroyed.
Thus dereferencing such a pointer will result in undefined behavior.
|
70,506,761 | 70,516,169 | Why don't methods defined in classes in C++ need forward declarations when referring to methods that only show up later in the class? | Why is this a compilation error:
void f() {
g();
}
void g() {
}
but not this:
class X {
void a() {
b();
}
void b() {
}
};
I was under the assumption the compiler would (at least, generally) read code from top-down, left-to-right, and that was the reason that in the 1st piece of code we'd need to define a void g() forward declaration before f() to make the code compile. But that logic doesn't seem to apply to classes -- why?
| C dates from 1972; C++ dates from 1985. C++ inherited the forward declaration requirement and the design of header files from C, and kept that behavior for compatibility, but was able to improve things for classes, with C didn't have.
|
70,506,780 | 70,508,058 | Member by member assignment of different classes based on the same template | Say that one has two classes which are different, but are somewhat "equivalent" in their purpose, so they have the same members, and one can be assigned by the other:
struct Pure
{
QString name;
int age = 18;
};
struct Observable
{
QProperty<QString> name;
QProperty<int> age {18};
void operator=(const Pure& other)
{
name = other.name;
age = other.age;
}
};
QProperty is a template class from Qt, but I think the question is Qt-independent, as it would apply to any other template <typename T> class Foo which has a conversion/assignment to/from T.
The question is how to avoid the duplication, so one cannot so easily add or remove a member from one class and forget doing it on the other, while still retaining the possibility of assigning an object of one class to another.
I've attempted several things with templates, and this seems the most promising:
// Adding two helpers only available in C++ 20 for convenience.
template<typename T>
struct type_identity { using type = T; };
template<typename T>
using type_identity_t = typename type_identity<T>::type;
template<template<typename T> typename T>
struct State
{
T<QString> name;
T<int> age;
// std::enable_if_t<std::is_same<QProperty<class X>, T>>
// operator=(const State<type_identity_t>& other)
// {
// name = other.name;
// age = other.age;
// }
};
int main()
{
State<type_identity_t> state;
state.age = 42;
State<QProperty> observableState;
observableState = state; // Desired use. Fails to compile without operator=
}
The commented out code doesn't compile (error: use of template template parameter 'T' requires template arguments), with the error at the T at the end of the first commented line, but I don't know how to fix this.
| You can't use std::is_same<QProperty<class X>, T>, because this is trying to pass T as the second argument to is_same, but it's a template and is_same is expecting a type.
You can make a is_same-like trait that takes template classes instead:
template<template<typename...> class A, template<typename...> class B>
struct is_same_template_class : std::false_type {};
template<template<typename...> class T>
struct is_same_template_class<T, T> : std::true_type {};
// use `is_same_template_class<T, QProperty>`
Currently, there doesn't seem to be a reason to limit what your operator= can do. Why not something like:
template<template<typename> class T>
struct State
{
T<QString> name;
T<int> age;
template<template<typename> class U>
State& operator=(const State<U>& other)
{
name = other.name;
age = other.age;
return *this;
}
};
And I am not familiar with QT, but it seems like using Observable = QProperty<Pure>; may also work if you refactor some of your logic.
|
70,506,857 | 70,507,316 | Why is this optimized away by modern compilers for C++11 and higher | I'm lost.. I wanted to play around with the compiler explorer to experiment with multithreaded C code, and started with a simple piece of code. The code is compiled with -O3.
static int hang = 0;
void set_hang(int x) {
hang = x;
}
void wait() {
while (hang != 0) {
// wait...
}
}
To my surprise, this was the compiler output:
set_hang(int):
mov dword ptr [rip + hang], edi
ret
wait():
ret
It took me a while before I noticed that I was compiling the code as C++ instead of C. Switching to C gave me something what I would have expected:
set_hang:
mov DWORD PTR hang[rip], edi
ret
wait:
mov eax, DWORD PTR hang[rip]
test eax, eax
je .L3
.L5:
jmp .L5
.L3:
ret
Thus, when compiled as C++, wait() always returns, no matter which value was passed before to set_hang(). I confirmed this by compiling and the code on my PC. This code immediately exists, while I would expect it to hang foreever:
int main(void) {
set_hang(1);
wait();
return 0;
}
And indeed, if I compile this with gcc instead of with g++, it hangs.
I experimented with different compilers (Clang and GCC), and this only happens with Clang 12.0.0 or higer or GCC 10.1 or higher. If I pass --std=c++98 also the code I would expect is emitted, so it seems to be something specific for C++11 and higher.
Removing the static keyword from the hang doesn't affect the emitted assembly.
What is happening here? It has been a few months since I wrote C++, so I might be missing some knowledge about the latest and greatest exotic C++ black magic, but this is really straightforward code. I'm clueless.
Edit: Even this program is optimized away completely:
// test.cpp
static int hang = 0;
static void set_hang(int x) {
hang = x;
}
static void wait() {
while (hang != 0) {
// wait...
}
}
int main(void) {
set_hang(1);
wait();
return 0;
}
Compiler output:
main:
xor eax, eax
ret
For GCC version 10.3.0 on Ubuntu:
This command will hang: g++ -O1 -o test test.cpp && ./test
And this command won't: g++ -O2 -o test test.cpp && ./test
| It's because of following rule:
[intro.progress]
The implementation may assume that any thread will eventually do one of the following:
terminate,
make a call to a library I/O function,
perform an access through a volatile glvalue, or
perform a synchronization operation or an atomic operation.
The compiler was able to prove that a program that enters the loop will never do any of the listed things and thus it is allowed to assume that the loop will never be entered.
|
70,507,626 | 70,507,744 | Overloading operator in different ways depending on template argument | I have a class
template<int n> MyClass<n>
for which I am trying to define the operator &. I want to be able to perform MyClass&MyClass, but also MyClass&MyClass<1> (or MyClass<1>&MyClass would work for me as well) with a different functionality obviously.
template <size_t n>
struct MyClass
{
//...a lot of stuff
MyClass<n> operator&(const MyClass<n> &other) const;
MyClass<n> operator&(const MyClass<1> &other) const;
}
However, I am not able to compile this, as for the case of n being 1 they collide. I tried adding SFINAE, but apparently I don't understand it well enough to use it in this case.
template <size_t n>
struct MyClass
{
//...a lot of stuff
MyClass<n> operator&(const MyClass<n> &other) const;
std::enable_if_t<n != 1, MyClass<n>> operator&(const MyClass<1> &other) const;
}
Does not work for making sure the case of n being 1 doesn't cause issues. I think it is because SFINAE works for the function template parameters itself, but not the class template parameters.
I believe I could to a specialization of MyClass<1>, but then I would have to replicate all the contents of MyClass<n>. Is there any easy solution to this?
| SFINAE only works with templates. You can make the 1st operator& template as:
template <size_t n>
struct MyClass
{
//...a lot of stuff
template <size_t x>
std::enable_if_t<x == n, MyClass<x>> // ensure only MyClass<n> could be used as right operand
operator&(const MyClass<x> &other) const;
// overloading with the template operator&
// non-template is perferred when MyClass<1> passed
MyClass<n> operator&(const MyClass<1> &other) const;
};
LIVE
|
70,507,682 | 70,508,191 | Wrong input shape error in torchscript and C++ interface | I am trying to interface libtorch and OpenCV to predict the classes using the Yolov5 model. The weight I am using is yolov5s.pt. The source code is
cv::Mat image = file->input_image(); // read image and resize into 640x640
auto tensor = torch::from_blob(image.data, {image.rows,image.cols,3}, torch::kFloat);
tensor = tensor.view({1,640,640,3});
std::cout << tensor.sizes() << std::endl;
try {
auto output = model.forward({tensor}).toTensor();
std::cout << output.sizes() << std::endl;
} catch (std::runtime_error & e) {
std::cerr << "[X] Error: " << e.what() << std::endl;
return;
}
Error message
RuntimeError: Given groups=1, weight of size [32, 3, 6, 6], expected input[1, 640, 640, 3] to have 3
channels, but got 640 channels instead
Traceback
Traceback of TorchScript, serialized code (most recent call last):
File "code/__torch__/models/yolo.py", line 59, in forward
model23 = self.model
_0 = getattr(model23, "0")
_25 = (_2).forward((_1).forward((_0).forward(x, ), ), )
~~~~~~~~~~~ <--- HERE
_26 = (_4).forward((_3).forward(_25, ), )
_27 = (_6).forward((_5).forward(_26, ), )
File "code/__torch__/models/common.py", line 12, in forward
act = self.act
conv = self.conv
_0 = (act).forward((conv).forward(x, ), )
~~~~~~~~~~~~~ <--- HERE
return _0
class C3(Module):
File "code/__torch__/torch/nn/modules/conv.py", line 12, in forward
bias = self.bias
weight = self.weight
x0 = torch._convolution(x, weight, bias, [2, 2], [2, 2], [1, 1], False, [0, 0], 1, False, False, True, True)
~~~~~~~~~~~~~~~~~~ <--- HERE
return x0
| The solution was pretty simple. I am feeling too embarrassing, but you shouldn't.
Here is the solution
// forgot to add these both lines
// the yolov5 is expects [BATCH, CHANNEL, WIDTH, HEIGHT]
tensor = tensor.permute({2,0,1});
tensor = tensor = tensor.unsqueeze(0);
std::cout << tensor.sizes() << std::endl;
|
70,508,180 | 70,508,229 | what is the "written out" equivalent of a ternary assignment? | I have a struct that is non-default-constructibe.
I want to assign different values to an object of that struct depending on a condition.
Since the struct is non-default-constructibe, it is not possible to declare an unitialized object of it.
However, it is possible to do that with a ternary:
struct foo {
foo(int a);
};
foo generateFoo1() {
return foo(1);
}
foo generateFoo2() {
return foo(2);
}
int main() {
bool test = false;
//compiles fine
foo f = test ? generateFoo1() : generateFoo2();
//the following does not compile
foo f2;
if(test) {
f2 = generateFoo1();
}else {
f2 = generateFoo2();
}
}
What would be a "written out" equivalent of the ternary assignment?
I have simplicity in mind and the ternary is a thorn in my eye. I would like to keep it as clean/readable as possible.
| Adding a factory function can help you out here. Using
foo make_foo(bool test)
{
if (test)
return generateFoo1();
else
return generateFoo2();
}
lets you have code like
foo f = make_foo(test);
|
70,508,536 | 70,516,877 | Need to add multiple inlcude devpkey.h in my cmake project in msvc | Included that header files of my BundleController class are included multiple times devpkey.h header file. So MSVC give errors like below;
**Severity Code Description Project File Line Suppression State
Error C2374 'DEVPKEY_Device_Address': redefinition; multiple initialization (compiling source file BundleController.cpp) C:\Program Files (x86)\Windows Kits\10\Include\10.0.22000.0\shared\devpkey.h 66
Error C2374 'DEVPKEY_Device_Address': redefinition; multiple initialization (compiling source file main.cpp) C:\Program Files (x86)\Windows Kits\10\Include\10.0.22000.0\shared\devpkey.h 66
Error C2374 'DEVPKEY_Device_AssignedToGuest': redefinition; multiple initialization (compiling source file BundleController.cpp) C:\Program Files (x86)\Windows Kits\10\Include\10.0.22000.0\shared\devpkey.h 167
Error C2374 'DEVPKEY_Device_AssignedToGuest': redefinition; multiple initialization (compiling source file main.cpp) C:\Program Files (x86)\Windows Kits\10\Include\10.0.22000.0\shared\devpkey.h 167
Error C2374 'DEVPKEY_Device_BaseContainerId': redefinition; multiple initialization (compiling source file Bundlecontroller.cpp) C:\Program Files (x86)\Windows Kits\10\Include\10.0.22000.0\shared\devpkey.h 74
Error C2374 'DEVPKEY_Device_BaseContainerId': redefinition; multiple initialization (compiling source file main.cpp) C:\Program Files (x86)\Windows Kits\10\Include\10.0.22000.0\shared\devpkey.h 74
Error C2374 'DEVPKEY_Device_BiosDeviceName': redefinition; multiple initialization (compiling source file BundleController.cpp) C:\Program Files (x86)\Windows Kits\10\Include\10.0.22000.0\shared\devpkey.h 153
Error C2374 'DEVPKEY_Device_BiosDeviceName': redefinition; multiple initialization (compiling source file main.cpp) C:\Program Files (x86)\Windows Kits\10\Include\10.0.22000.0\shared\devpkey.h 153
.
.
.**
I need to include multiple times devpkey.h header file to my project, how can I add that file?
Project compilation tool is cmake.
| in such situation always need look code and try understand source of error. DEVPKEY_Device_Address (and another symbols in question) defined with DEFINE_DEVPROPKEY macro. based on - are INITGUID is defined - DEFINE_DEVPROPKEY expanded to declaration or definition. if not defined INITGUID, before include devpkey.h ( usually this is done not direct but by #include <initguid.h>, because here exist additional important macros ), we will be have only declarations of DEVPKEY_Device_Address and other symbols, without actual definitions. as result we got error - unresolved symbol on link time. if include initguid.h before every include devpkey.h - we will be have multiple definitions of symbols. usual this must not lead to error, because was DECLSPEC_SELECTANY in symbol definition, which can expand to __declspec( selectany )
Tells the compiler that the declared global data item (variable or object) is a pick-any COMDAT (a packaged function).At link time, if
multiple definitions of a COMDAT are seen, the linker picks one and
discards the rest.
but look like your comiler dont support/understand __declspec( selectany ), if you got error C2374
in this case - need have declaration in any file, which use symbol and definition only in any one. for this in some selected source file do
#include <initguid.h>
// ...
#include <devpkey.h>
and in another files - only
#include <devpkey.h>
without #include <initguid.h> before
|
70,508,626 | 70,508,942 | C++ can't use std::array, due to cli::array keyword Visual Studio | I want to declare a std::array, but the array part gets recognized as cli::array keyword (see Why is "array" marked as a reserved word in Visual-C++?), which means that the std:: doesnt affect it. How can a stop Visual Studio from automatically using namespace cli, or specify that I want to use std::array?
The blue array-word recognized as keyword
| std::array accepts two template arguments. One is the type of the elements and the other accepts the number of elements.
If you mean to use a dynamic array, then use std::vector.
|
70,508,730 | 70,511,136 | How to parse a string of a set of chess moves and store each move individually C++ | So I am reading a .txt file that has many sets of chess moves. I am able to read data from the file and insert the line into a string.
An example single chess move can look like this:
1. e4 e5
I have written the following function to parse a single chess move:
void parseSingleChessMove(string move)
{
this->moveNumber = stoi(move.substr(0, move.find(".")));
this->move[0] = move.substr(move.find_first_of(" ")+1, move.find_last_of(" ")-move.find_first_of(" ")-1);
this->move[1] = move.substr(move.find_last_of(" ")+1);
}
I am parsing the string and storing it within a self-defined Move Class hence the use of the 'this' operator. This function works perfectly and stores each field of a single chess move. move[0] stores the first move and move[1] stores the second move, while the moveNumber data member stores the number the move was played at.
I am creating an array of the Move Class in order to store every single move of a chess match in order. However, a complete set of chess moves can look something like this:
1. Nf3 Nf6 2. c4 c6 3. g3 g6 4. b3 Bg7 5. Bb2 O-O 6. Bg2 d5 7. O-O Bf5 8. d3
Nbd7 9. Nd4 e6 10. h3 h5
I am having a hard time trying to figure out how to store each of these individual moves in the array of Move Class from a string of a set of chess moves.
The main issue is reading the string only until a move number is found. I then need to obtain a substring for a move (something like 4. b3 Bg7and then parsing this single chess move using the above function so that I can store moveNumber=4, move[0]="b3" and move[1]="Bg7" and finally storing it into the respective index of array type Move Class. And then repeating this until all moves are stored one by one and we reach the end of the string.
EDIT: This is my class definition:
class MoveNode {
public:
array<string, 2> move;
int moveNumber;
void parseSingleChessMove(string move)
{
this->moveNumber = stoi(move.substr(0, move.find(".")));
this->move[0] = move.substr(move.find_first_of(" ")+1, move.find_last_of(" ")-move.find_first_of(" ")-1);
this->move[1] = move.substr(move.find_last_of(" ")+1);
}
}
I am storing all of the moves in this array:
MoveNode *setofMoves = new MoveNode[totalMoves];
| @rturrado showcased how you could do this with regex, however I would hesitate to do it like that, since std::regex is heavy, and requires a lot of knowledge regarding regex to use it effectively. Instead, I think it's easier to accomplish it with istream and operator>>.
void parse_moves(std::istream& input)
{
int move_number;
char dot;
std::string move_fisrt, move_second;
int index = 0;
while(input >> move_number >> dot >> move_first >> move_second)
{
setofMoves[index] = MoveNode{{move_first, move_second}, move_number};
++index;
}
}
Here while(is >> ...) will keep parsing the text as long it's following the pattern.
|
70,508,815 | 70,508,966 | Implicit call of Class constructor from Initialisation of another class | The following code-snippet seemingly works:
#include <iostream>
class Filling{
public:
const int num;
Filling(int num_)
: num(num_)
{ }
};
class Nougat{
public:
Nougat(const Filling& filling)
: reference(filling)
{ }
const Filling& get_filling() const{ return reference; }
private:
const Filling& reference;
};
class Wrapper{
public:
Wrapper(const Nougat& nougat)
: reference(nougat)
{ }
const Nougat& get_nougat() const{ return reference; };
private:
const Nougat& reference;
};
int main(){
Filling filling(3);
Wrapper wrap(filling); /*(0)*/
std::cout << wrap.get_nougat().get_filling().num << std::endl;
}
Although the initialisation is improper (at /*(0)*/), because the Wrapper class should accept a Nougat class, but instead it is given a Filling class.
Since the constructor takes references, I believe the compiler is creating a temporary Nougat class from the constructor argument, and then passes that to initialise the Wrapper class.
Getting a reference from a temporary results in undefined behaviour.
Is this what is really happening?
If so, how can this code compile?
| Wrapper's constructor expects a reference to Nougat, but you are giving it a Filling. As with all function calls in C++, in such a situation implicit conversion sequences for all arguments are considered.
An implicit conversion sequence could be for example a cast from a derived class reference to a base class reference, but since Nougat and Filling are not related in that way, this doesn't apply here.
Another allowed step in an implicit conversion sequence are user-defined conversions. This also includes so-called converting constructors of the target type, that is a constructor not marked explicit. This is the case for the constructor Nougat(const Filling& filling), which allows for conversion from Filling to Nougat.
So, this constructor may be called to construct a temporary object of Nougat type as an implicit conversion. The resulting temporary can bind to a const lvalue reference as well.
To avoid such unintentional conversions, you should mark constructors as explicit, at least if they take exactly one argument, except if you really intent for such implicit conversions to happen.
By the end of the construction of wrapper, the temporary object is destroyed and therefore the reference obtained in
wrap.get_nougat()
is dangling, and it's following use causes undefined behavior.
|
70,508,837 | 70,508,875 | I want to know the error in my code. This is to print sum of all even numbers till 1 to N | #include<iostream>
using namespace std;
int main(){
int i = 1;
int sum;
int N;
cout << "Enter a number N: ";
cin >> N;
while(i<=N)
{
if(i%2 == 0)
{
sum = sum + i;
}
else
{
i = i + 1;
}
}
cout << sum;
}
This is to print the sum of all even numbers till 1 to N.
As I try to run the code, I am being asked the value of N but nothing is being printed ahead.
| For starters the variable sum is not initialized.
Secondly you need to increase the variable i also when it is an even number. So the loop should look at least like
while(i<=N)
{
if(i%2 == 0)
{
sum = sum + i;
}
i = i + 1;
}
In general it is always better to declare variables in minimum scopes where they are used.
So instead of the while loop it is better to use a for loop as for example
for ( int i = 1; i++ < N; ++i )
{
if ( i % 2 == 0 ) sum += i;
}
|
70,509,028 | 70,509,256 | writting a binary in c++ | So i have this program that supposedly reads any file (e.g images, txt) and get its data and creates a new file with that same data. The problem is that i want the data in an array and not in a vector and when i copy that same data to char array, whenever i try to write those bits into a file it doesnt write the file properly.
So the question is how can i get the data from std::ifstream input( "hello.txt", std::ios::binary ); and save it an char array[] so that i can write that data into a new file?
Program:
#include <stdlib.h>
#include <string.h>
#include <fstream>
#include <iterator>
#include <vector>
#include <iostream>
#include <algorithm>
int main()
{
FILE *newfile;
std::ifstream input( "hello.txt", std::ios::binary );
std::vector<unsigned char> buffer(std::istreambuf_iterator<char>(input), {});
char arr[buffer.size()];
std::copy(buffer.begin(), buffer.end(), arr);
int sdfd;
sdfd = open("newhello.txt",O_WRONLY | O_CREAT);
write(sdfd,arr,strlen(arr)*sizeof(char));
close(sdfd);
return(0);
}
| Try this:
(It basically uses a char*, but it's an array here. You probably can't have an array in the stack in this case)
#include <iostream>
#include <fstream>
int main() {
std::ifstream input("hello.txt", std::ios::binary);
char* buffer;
size_t len; // if u don't want to delete the buffer
if (input) {
input.seekg(0, input.end);
len = input.tellg();
input.seekg(0, input.beg);
buffer = new char[len];
input.read(buffer, len);
input.close();
std::ofstream fileOut("newhello.txt");
fileOut.write(buffer, len);
fileOut.close();
// delete[] buffer; u may delete the buffer or keep it for further use anywhere else
}
}
This should probably solve your problem, remember to always have the length (len here) of the buffer if you don't want to delete it.
More here
|
70,509,085 | 70,509,191 | Print of vowels in a string | I attempted to create a program that let's the user input a string of text and then create a subprogram that will print out all the vowels in that string. The problem with my program is that it only prints out the text once again.
So my terminal will look like:
Enter text: Feye
Feye
Instead of what I intend it to do:
Enter text: Feye
eye
This is my code and I wonder what's wrong of it. Why doesn't it print out the index like I ordered it to do in my if-statement?
#include <iostream>
using namespace std;
void print_vowels (string const & text)
{
for (int i {}; i < text.size(); ++i)
{
if (text.at(i) == 'a' || 'e' || 'i' || 'o' || 'u' || 'y')
{
cout << text.at(i);
}
}
}
int main()
{
string text {};
cout << "Enter text: ";
getline(cin,text);
print_vowels(text);
return 0;
}
I have also tried putting text[i] instead of text.at(i) but I get the same results unfortunately.
| Here is a simple solution:
#include <iostream>
#include <string>
#include <string_view>
#include <array>
#include <iterator>
#include <algorithm>
static constexpr std::array<char, 12> vowels { 'A', 'E', 'I', 'O', 'U', 'Y',
'a', 'e', 'i', 'o', 'u', 'y' };
bool is_vowel( const char ch )
{
return ( std::end( vowels ) != std::find( begin( vowels ),
end( vowels ), ch ) );
}
bool is_consonant( const char ch )
{
if ( ( ch >= 'A' && ch <= 'Z' ) ||
( ch >= 'a' && ch <= 'z' ) )
{
return ( std::end( vowels ) == std::find( begin( vowels ),
end( vowels ), ch ) );
}
return false;
}
void print_vowels( const std::string_view text )
{
for ( const char ch : text )
{
if ( is_vowel( ch ) ) { std::cout << ch; }
}
}
void print_consonants( const std::string_view text )
{
for ( const char ch : text )
{
if ( is_consonant( ch ) ) { std::cout << ch; }
}
}
int main( )
{
std::string text { };
std::cout << "Enter text: ";
std::getline( std::cin, text );
std::cout << "vowels: ";
print_vowels( text );
std::cout << "\nconsonants: ";
print_consonants( text );
}
Also, note that at member function has a performance hit since it also checks for out-of-range indices at run-time. So it's better to use the [] operator or a range-based for-loop in this case.
Sample input/output:
Enter text: Feye
vowels: eye
consonants: F
Another sample:
Enter text: Apple
vowels: Ae
consonants: ppl
Another one:
Enter text: Or#an.ge(-=
vowels: Oae
consonants: rng
Read about std::find here.
|
70,509,208 | 70,509,470 | std::future in simple words? | I saw the uses of std::future in the program written in C++. So, I quickly went to lookup what is is: std::future and got a quite complicated answer for me.
Can someone put it in simple words for a 6 years old kid? I have an understanding level of a 6 years old kid...
Just a small definition with a minimal use case will work for me. Let me know if it is too much to ask and I'll take back my question.
| A std::future<T> is a handle to a result of work which is [potentially] not, yet, computed. You can imagine it as the receipt you get when you ask for work and the receipt is used to get the result back. For example, you may bring a bike to bike store for repair. You get a receipt to get back your bike. While the work is in progress (the bike being repaired) you can go about other business. Eventually, when the work is supposed to be done you ask for the result (the repaired bike) and [potentially] wait until the result is delivered.
std::future<T> is a general mechanism to receive result. It doesn't prescribe how the requested work is actually executed.
|
70,509,529 | 70,509,563 | Use of class template node requires template arguments C++ | I have two classes defined in C++ seen below.
#include <vector>
#include <tuple>
#include <map>
template <class T> class node {
public:
int NodeID; //ID used to identify node when inserting/deleting/finding.
T data; //generic data encapsulated in each node.
std::vector<node*> children; //child nodes, list of ptrs
std::vector<node*> parents; //parent nodes list of ptrs
};
class DAG {//Class for the graph
std::vector<node*> Nodes;
}
However I am getting an error within DAG saying "Use of class template node requires template arguments". I am completely lost any help is greatly appreciated.
| Solution 1
You can solve this by specifying a type in std::vector<node*> Nodes; as shown below:
std::vector<node<int>*> Nodes; //note i have added int you can add any type
Solution 2
Another solution would be to make class DAG a class template as shown below:
template<typename T>
class DAG {//Class for the graph
std::vector<node<T>*> Nodes;
};
|
70,509,642 | 70,524,080 | Dealing with in/out string parameters in Swig Python | Maybe someone know, how to rewrite getVersion to get in Python version and legacyVersion as a result of function instead of passing them as in/out parameters
class DeviceInterface {
public:
virtual uint32_t getVersion(uint8_t* version, uint8_t* legacyVersion ) = 0;
};
For now I create additional function in SWIG inteface file, but current implementation returns only one parameter instead of two.
%ignore DeviceInterface::getVersion( uint8_t* version, uint8_t* legacyVersion );
%extend DeviceInterface {
virtual char * getVersion() {
static uint8_t _v[200];
static uint8_t _lv[200];
$self->getVersion(_v, _lv);
return (char *)_lv;
}
};
UPDATE
Now I use @ignore and @extend features. But I guess there is more elegant way. Here is my working SWIG interface snippet:
%extend DeviceInterface {
virtual PyObject *getVersion() {
static uint8_t _v[200];
static uint8_t _lv[200];
uint32_t libCode = $self->getVersion(_v, _lv);
return Py_BuildValue("(l,s,s)", libCode, (char *)_v, (char *)_lv);
}
};
| You can define your own typemaps to handle the output parameters. In this case, the typemaps treat all uint32_t* parameters as 200-byte output buffers. This is a minimal example without error checking.
%module test
%include <stdint.i>
// Require no input parameter. Just allocate a fixed-sized buffer.
%typemap(in,numinputs=0) uint8_t* %{
$1 = new uint8_t[200];
%}
// Free the temporary buffer when done converting the argument
%typemap(freearg) uint8_t* %{
delete [] $1;
%}
// On output, convert the buffer to a Python byte string
%typemap(argout) uint8_t* %{
$result = SWIG_Python_AppendOutput($result, PyBytes_FromString(reinterpret_cast<char*>($1)));
%}
// Example implementation
%inline %{
#include <stdint.h>
class DeviceInterface {
public:
virtual uint32_t getVersion(uint8_t* version, uint8_t* legacyVersion ) {
strcpy(reinterpret_cast<char*>(version),"1.0.0");
strcpy(reinterpret_cast<char*>(legacyVersion),"2.0.0");
return 0;
}
};
%}
Output:
>>> import test
>>> d=test.DeviceInterface()
>>> d.getVersion()
[0, b'1.0.0', b'2.0.0']
Note the output is a concatenation of the return value and two output parameters.
|
70,510,716 | 70,511,014 | Why we cannot create an array with a constant in c | Why the below piece is a valid C++ code but an - invalid C code?
int main(){
unsigned int const size_of_list = 20;
const char* list_of_words[size_of_list] = {"Some", "Array"};
for (unsigned int writing_index = 0; writing_index < size_of_list; writing_index ++)
;
return 0;
}
| In C:
20 is a constant.
unsigned int const size_of_list is not a constant.
Title: "Why we cannot create an array with a constant in c" does not apply to this code.
const char* list_of_words[size_of_list] = {"Some", "Array"}; // Bad
An issue here (and the error message) is why a VLA cannot be initialized. That is answered here.
With a constant, array initialization works fine.
const char* list_of_words[20] = {"Some", "Array"}; // Good
Another issue is mistaking that const makes an object a constant. It does not.
Alternative C code
int main(){
// unsigned int const size_of_list = 20;
#define size_of_list 20u
const char* list_of_words[size_of_list] = {"Some", "Array"};
for (unsigned int writing_index = 0; writing_index < size_of_list; writing_index ++)
;
return 0;
}
If you can specify the size in the array itself, then you can get it's size with the sizeof operator. This may be better suited for having the compiler count up the size instead manual counting. When not using C99 VLAs, sizeof also yields a compile-time constant.
#include <stddef.h> /* size_t */
int main(void) {
const char* list_of_words[] = {"Some", "Array"};
const char list_of_char[sizeof list_of_words
/ sizeof *list_of_words] = {'S','A'};
const size_t size_of_list
= sizeof list_of_words / sizeof *list_of_words;
for (size_t writing_index = 0;
writing_index < size_of_list; writing_index ++);
return 0;
}
|
70,511,046 | 70,511,442 | Parsing a string in c++ with a specfic format | I have this string post "ola tudo bem como esta" alghero.jpg and i want to break it into 3 pieces post, ola tudo bem como esta (i dont want the "") and alghero.jpg i tried it in c because im new and not really good at programming in c++ but its not working. Is there a more efficient way of doing this in c++?
Program:
int main()
{
char* token1 = new char[128];
char* token2 = new char[128];
char* token3 = new char[128];
char str[] = "post \"ola tudo bem como esta\" alghero.jpg";
char *token;
/* get the first token */
token = strtok(str, " ");
//walk through other tokens
while( token != NULL ) {
printf( " %s\n", token );
token = strtok(NULL, " ");
}
return(0);
}
| In C++14 and later, you can use std::quoted to read quoted strings from any std::istream, such as std::istringstream, eg:
#include <iostream>
#include <sstream>
#include <string>
#include <iomanip>
int main()
{
std::string token1, token2, token3;
std::string str = "post \"ola tudo bem como esta\" alghero.jpg";
std::istringstream(str) >> token1 >> std::quoted(token2) >> token3;
std::cout << token1 << "\n";
std::cout << token2 << "\n";
std::cout << token3 << "\n";
return 0;
}
|
70,511,082 | 70,515,855 | Why is it possible to pass a void(*)(int x, int y) to attachInterrupt that expects void(*)()? | I've been inattentive and for some reason created a function that takes two arguments, and I passed it to attachInterrupt like so:
int state = 42;
void simplified_state_handler(){
state++;
}
void interrupt_func(int x, int y) {
simplified_state_handler();
}
attachInterrupt(digitalPinToInterrupt(10), interrupt_func, CHANGE);
The code got compiled with no complaints at all, and it even works. Now, a bit later, I really can't understand why. Reading and digging the attachInterrupt code didn't help. Please explain why can I pass such a function at all. I'm keeping the (now) useless simplified_state_handler in the example, maybe it is important.
| The compiler settings of the AVR boards allow it.
It is only a warning: invalid conversion from 'void (*)(int, int)' to 'void (*)()' [-fpermissive].
On other Arduino platforms (SAMD, STM32, esp8266) it is an error.
The compiler settings in AVR platform were benevolent from the start and they can't change them suddenly. Many existing codes would not compile then.
|
70,511,444 | 70,511,645 | Is it possible to have a constructor with 1 input parameter of undeclared type? | Here is what I an trying to do:
Class with two objects (string myStr and int myInt)
Constructor takes in 1 parameter (data type not fixed).
If parameter is string: myStr = parameter; myInt = parameter.length();
If parameter is int: myInt = parameter; myStr = "0000...0"
(string of length "parameter", set by for loop)
Else : cout << "Error";
Is it possible to do what I am describing in line 2?
I've managed to do some workarounds using only strings and converting data types (able to do this when imposing an artificial lower bound for length of myStr) however this is causing me other issues further down the line.
|
Is it possible to have a constructor with 1 input parameter of undeclared type?
Technically, you can have variadic parameters which allows unspecified number of arguments of unspecified types. But I recommend against using it.
The types of all other parameters must be declared.
If parameter is string: myStr = parameter; myInt = parameter.length();
If parameter is int: myInt = parameter; myStr = "0000...0" (string of length "parameter", set by for loop)
You can easily achieve this using two constructors instead of one. One that accepts a string and another that accepts an integer.
|
70,512,077 | 70,512,136 | multiple concepts for template class | I have the class below, but it only works with floating points. How to add integers too? That is multiple requires statements? or is there something that can include all numerical types?
Or there is a better way?
#ifndef COMPLEX_H
#define COMPLEX_H
#include <concepts>
#include <iostream>
template <class T>
requires std::floating_point<T> // How to add integral, signed integral, etc
class Complex {
private:
T re = 0;
T im = 0;
public:
Complex() {
std::cout << "Complex: Default constructor" << std::endl;
};
Complex(T real) : re{re} {
std::cout << "Complex: Constructing from assignement!" << std::endl;
};
bool operator<(const Complex<T>& other) {
return re < other.re && im < other.im;
}
};
#endif // COMPLEX_H
| You can || your concepts such as
requires std::floating_point<T> || std::integral<T>
you can also create a concept this way
template <typename T>
concept arithmetic = std::integral<T> || std::floating_point<T>;
then you can use this concept with your class
template <class T>
requires arithmetic<T>
class Complex
{
...
|
70,512,367 | 70,608,511 | How to translate a program into a language with QtLinguist in C++? | I wrote code on QtCreator to translate the GUI of my application into English and Spanish. This application was written in French. The .ts translation files have been generated. And I translated strings to English on QtLinguist (but not Spanish), and I ticked the fields with a green arrow to show that I was sure of the translation. But when I generated the files .qm thanks to lrelease, the IDE wrote:
Updating 'C:/Users/user/Documents/ZeroClassGenerator/zeroclassgenerator_en.qm'...
Generated 3 translation(s) (3 finished and 0 unfinished)
Updating 'C:/Users/user/Documents/ZeroClassGenerator/zeroclassgenerator_es.qm'...
Generated 0 translation(s) (0 finished and 0 unfinished)
Ignored 3 untranslated source text(s)
"C:\QtSdk2\6.2.1\mingw81_64\bin\lrelease.exe" finished
But the text to be translated has not been translated into English. However, I put the .qm file in the same folder as the executable of my software and I wrote the following code in the main file:
#include "FenPrincipale.h"
#include <QApplication>
#include <QTranslator>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTranslator translator;
translator.load("zeroclassgenerator_en");
a.installTranslator(&translator);
FenPrincipale fenetre;
fenetre.show();
return a.exec();
}
Since that code didn't work, I wrote this one.
#include "FenPrincipale.h"
#include <QApplication>
#include <QTranslator>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTranslator translator;
if( translator.load("zeroclassgenerator_en"))
a.installTranslator(&translator);
FenPrincipale fenetre;
fenetre.show();
return a.exec();
}
I don't know where I went wrong.
| What probably happens is that QTranslator::load fails; since you didn't specify an absolute path, nor did you pass a directory as second argument, it will only try to find the file in your current working directory.
To make this more robust, you should a) specify the directory as second argument, and b) check the return value of installTranslator():
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTranslator translator;
if (!translator.load("zeroclassgenerator_en", QApplication::applicationDirPath()))
qWarning("Could not load translation file");
a.installTranslator(&translator);
FenPrincipale fenetre;
fenetre.show();
return a.exec()
}
|
70,512,466 | 70,513,480 | Getting undefined symbols for architecture arm64 error | I am building on an M1 Pro Mac (CLion) and am getting the following error while compiling:
FAILED: tree
: && /Library/Developer/CommandLineTools/usr/bin/c++ -g -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.0.sdk -Wl,-search_paths_first -Wl,-headerpad_max_install_names CMakeFiles/tree.dir/main.cpp.o CMakeFiles/tree.dir/Node.cpp.o CMakeFiles/tree.dir/Tree.cpp.o CMakeFiles/tree.dir/Unit.cpp.o -o tree && :
Undefined symbols for architecture arm64:
"Node<Unit>::addRoot(Unit)", referenced from:
_main in main.cpp.o
"Node<Unit>::Node()", referenced from:
_main in main.cpp.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
ninja: build stopped: subcommand failed.
I have three classes, Node, Tree and Unit. Most of the posts I have come across suggests that one of the files are not included in the project (eg Undefined symbols for architecture arm64 using g++ compiler). I doubt this is the issue, since they all appear to be included in the compiler line.
My CMakeLists.txt looks like this:
cmake_minimum_required(VERSION 3.21)
project(tree)
set(CMAKE_CXX_STANDARD 14)
add_executable(tree main.cpp Node.cpp Node.h Tree.cpp Tree.h Unit.cpp Unit.h)
I am adding the header file for the Unit class since this seems to be the one that offends the compiler, however I doubt this is where the issue lies. Guessing it is some make file setup?
#include <iostream>
#include <vector>
using namespace std;
template <class T>
class Node {
weak_ptr<Node> parent;
vector<shared_ptr<shared_ptr<Node>>> children;
T data;
public:
Node();
Node(weak_ptr<Node> parent, T &data);
void addRoot(T node_data);
};
And at risk of being too verbose in this post, here is the CMakeError.log output:
Compiling the C compiler identification source file "CMakeCCompilerId.c" failed.
Compiler: /Library/Developer/CommandLineTools/usr/bin/cc
Build flags:
Id flags:
The output was:
1
ld: library not found for -lSystem
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Compiling the CXX compiler identification source file "CMakeCXXCompilerId.cpp" failed.
Compiler: /Library/Developer/CommandLineTools/usr/bin/c++
Build flags:
Id flags:
The output was:
1
ld: library not found for -lc++
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Output if I run c++ main.cpp Node.cpp Tree.cpp Unit.cpp:
In file included from main.cpp:3:
./Node.h:16:38: error: a space is required between consecutive right angle brackets (use '> >')
vector<shared_ptr<shared_ptr<Node>>> children;
^~
> >
main.cpp:7:5: warning: 'auto' type specifier is a C++11 extension [-Wc++11-extensions]
auto unit = std::make_unique<Unit>(1, "Test Unit");
^
main.cpp:7:22: error: no member named 'make_unique' in namespace 'std'
auto unit = std::make_unique<Unit>(1, "Test Unit");
~~~~~^
main.cpp:7:34: error: 'Unit' does not refer to a value
auto unit = std::make_unique<Unit>(1, "Test Unit");
^
./Unit.h:11:7: note: declared here
class Unit {
^
main.cpp:7:40: warning: expression result unused [-Wunused-value]
auto unit = std::make_unique<Unit>(1, "Test Unit");
^
main.cpp:8:20: error: expected ';' at end of declaration
Node<Unit> node {};
^
;
2 warnings and 4 errors generated.
In file included from Node.cpp:5:
./Node.h:16:38: error: a space is required between consecutive right angle brackets (use '> >')
vector<shared_ptr<shared_ptr<Node>>> children;
^~
> >
1 error generated.
I am a relative new comer to C++ so am finding this issue somewhat troublesome to track down.
| It looks like you are having problems with templates. In templated classes you have to either place the implementation of the methods all in the header file or make explicit template instantiations of the concrete classes in the cpp body that defines it.
It's easier to see with an example. In the following case I'm adding the body of the constructor in the header so I dont' have to do anything else
/////////////////////////////////////////
// In Node.h
/////////////////////////////////////////
template< typename T >
struct Node {
Node();
};
template< typename T >
Node<T>::Node() {
}
/////////////////////////////////////////
// In Node.cpp
/////////////////////////////////////////
// (nothing)
/////////////////////////////////////////
// Int main.cpp
/////////////////////////////////////////
#include "Node.h"
int main() {
Node<int> n;
}
In the second case I will make an explicit template instantiation of the concrete class Node<int> in the body of Node.cpp such that I don't need to expose the implementation of the templated classes.
/////////////////////////////////////////
// In Node.h
/////////////////////////////////////////
template< typename T >
struct Node {
Node();
};
/////////////////////////////////////////
// In Node.cpp
/////////////////////////////////////////
template< typename T >
Node<T>::Node() {}
// Explicit initialization
template struct Node<int>;
/////////////////////////////////////////
// Int main.cpp
/////////////////////////////////////////
#include "Node.h"
int main() {
Node<int> n;
}
I prefer to use the 2nd method since it lowers build times significantly.
|
70,513,188 | 70,513,333 | JsonCpp: Serializing JSON causes loss of data in byte string | I have a simple use case where I wish to serialize and transmit vectors of integers between 0 and 256. I surmised that the most space-efficient way of doing so would be to serialize the vector as a serialized string, where the nth character has the ASCII code equivalent to the nth element of the corresponding vector. To this end, I wrote the following two functions:
std::string SerializeToBytes(const std::vector<int> &frag)
{
std::vector<unsigned char> res;
res.reserve(frag.size());
for(int val : frag) {
res.push_back((char) val);
}
return std::string(res.begin(), res.end());
}
std::vector<int> ParseFromBytes(const std::string &serialized_frag)
{
std::vector<int> res;
res.reserve(serialized_frag.length());
for(unsigned char c : serialized_frag) {
res.push_back(c);
}
return res;
}
However, when sending this data using JsonCpp, I run into issues. The minimum reproducible example below indicates that the issue does not stem from the above methods and instead appears only when a Json::Value is serialized and subsequently parsed. This causes the loss of some encoded data in the serialized string.
#include <cassert>
#include <json/json.h>
int main() {
std::vector frag = { 230 };
std::string serialized = SerializeToBytes(frag);
// Will pass, indicating that the SerializeToBytes and ParseFromBytes functions are not the issue.
assert(frag == ParseFromBytes(serialized));
Json::Value val;
val["STR"] = serialized;
// Will pass, showing that the issue does not appear until JSON is serialized and then parsed.
assert(frag == ParseFromBytes(val["STR"].asString()));
Json::StreamWriterBuilder builder;
builder["indentation"] = "";
std::string serialized_json = Json::writeString(builder, val);
// Will be serialized to "{\"STR\":\"\\ufffd\"}".
Json::Value reconstructed_json;
Json::Reader reader;
reader.parse(serialized_json, reconstructed_json);
// Will produce { 239, 191, 189 }, rather than { 230 }, as it should.
std::vector<int> frag_from_json = ParseFromBytes(reconstructed_json["STR"].asString());
// Will fail, showing that the issue stems from the serialize/parsing process.
assert(frag == frag_from_json);
return 0;
}
What is the cause of this issue, and how can I remedy it? Thanks for any help you can offer.
| Jsoncpp Class Value
This class is a discriminated union wrapper that can represents a:
...
UTF-8 string
...
{ 230 } is invalid UTF-8 string. Thus further expectations from Json::writeString(builder, val) for a correct result are illegal.
|
70,513,208 | 70,523,303 | STM32 - Dynamic Memory Allocation Implementation, how to correctly implement the _sbrk function? | I'm working on a bare-metal programming project written in C++ on a STM32F401RE board, and I need to implement malloc() and free() functions.
I know that dynamic memory allocation on embedded systems is not a good idea, but I need it.
Up to know I understood that in order to use malloc and free functions of the C standard library I need to manually implement a function named _sbkr(), and in order to do so I created a library with this single function and added it to the includes of the main.cpp source code.
The problem is that it doesn't work, when I try to dynamically allocate a variable it returns a NULL pointer.
Generating with gcc the assembly code of the main, it seems that the _sbrk function is not implemented in the final object which will be uploaded on the board.
How can I Correctly implement this function?
| Assuming that you are using Newlib (the usual C library used with GCC on stand-alone systems), then the target specific porting layer ("syscalls") for the C library is defined at https://sourceware.org/newlib/libc.html#Syscalls.
A minimal implementation suitable for standalone (no OS) environments is given there as an example:
caddr_t sbrk(int incr) {
extern char _end; /* Defined by the linker */
static char *heap_end;
char *prev_heap_end;
if (heap_end == 0) {
heap_end = &_end;
}
prev_heap_end = heap_end;
if (heap_end + incr > stack_ptr) {
write (1, "Heap and stack collision\n", 25);
abort ();
}
heap_end += incr;
return (caddr_t) prev_heap_end;
}
Note also that if you are using an RTOS or threading library you will also need to implement __malloc_lock() and __malloc_unlock() using your RTOS/thread libraries mutex call.
Note also that if you use ST's STM32CubeIDE that uses GCC and Newlib and has the syscalls layer implemented already.
|
70,513,252 | 70,513,306 | Is there a way to iterate over the second element of a std::map? | I want to create a std::vector<char> with something like: v(map.begin(), map.end()); rather than iterating over all elements of the map and resizing v over and over.
#include<iostream>
#include<map>
#include<vector>
int main() {
std::map<int, char> map{{1,'a'},{2,'b'},{3,'c'}, {4,'d'}};
std::vector<char> v;
for(auto& [ i , c ] : map){
// std::cout << i << " -> " << c <<"\n";
v.push_back(c);
}
}
| In C++20, you could create a view over the values by using std::views::values:
#include <map>
#include <vector>
#include <ranges>
int main() {
std::map<int, char> map{{1, 'a'}, {2, 'b'}, {3, 'c'}, {4, 'd'}};
auto view = std::views::values(map);
std::vector<char> v(view.begin(), view.end());
}
Demo
A more general purpose view is the std::views::transform where you supply the transformation to be done via a functor:
#include <map>
#include <vector>
#include <ranges>
int main() {
std::map<int, char> map{{1, 'a'}, {2, 'b'}, {3, 'c'}, {4, 'd'}};
auto view = map | std::views::transform([](auto&& p){ return p.second; });
std::vector<char> v(view.begin(), view.end());
}
Demo
|
70,513,264 | 70,513,342 | How is printf() an expression? | I was trying to learn value categories because of an error that I got and stared watching this video by Copper Spice.
They go on to define an expression and as an example provide printf() at this point in the video (screenshot below).
How is printf() an expression? I always thought that function calls aren't really an expression when written by themselves. They are more like statements as my beginner mind thinks of it. Moreover, the definition they provide mentions operators and operands but none can be seen with printf. What am I missing?
The data type that is mentioned is the return value for printf. What about functions that return void?
|
How is printf() an expression?
It's a function call expression.
I always that that function calls aren't really an expression
Function calls are expressions.
They are more like statements
Function calls are not statements. Consider for example ret = printf();. Here, the function call is a subexpression of the assignment expression. Statements cannot be sub expressions - expressions can be sub expressions.
Moreover, the definition they provide mentions operators and operands but none can be seen with printf.
The parentheses are the function call operator. The operands are the function (which is a postfix expression) on the left side of the parentheses and the argument list within the parentheses.
How is the expression characterized by a data type?
Every expression has a type. The type - along with the value category - affects how you can use the expression.
I thought that the data type was related to the return type of the printf function
You thought right. The type of a function call expression is determined by the return type of the function. The type of printf() is int.
|
70,513,509 | 70,513,536 | default member value initialization is ignored in GCC | I came up with an unexpected behaviour (to my own limited knowledge) in the code below, where it does not respect the default member initialized values. I have a contractor for a single argument assignment that supposes to build the class from an assignment operator. I forgot to use the correct argument name and I ended up with this problem (see the line with single argument constructor with intentional error:
Why do I get garbage values and not the member initialized value?
My own assumption was because of templated class, 0 is not the same as 0.0...but tried it with and got the same problem.
#include <iostream>
#include <concepts>
template <class T>
requires std::is_arithmetic_v<T>
class Complex
{
private:
T re = 0;
T im = 0;
public:
Complex() {
std::cout << "Complex: Default constructor" << std::endl;
};
Complex(T real) : re{re} { // should be re{real}, but why re{re} is not 0?
std::cout << "Complex: Constructing from assignement!" << std::endl;
};
void setReal(T t) {
re = t;
}
void setImag(const T& t) {
im = t;
}
T real() const {
return re;
}
T imag() const {
return im;
}
Complex<T>& operator+=(const Complex<T> other) {
re+= other.re;
im+= other.im;
return *this;
}
bool operator<(const Complex<T>& other) {
return (re < other.re && im < other.im);
}
};
int main() {
Complex<double> cA;
std::cout<< "cA=" << cA.real() << ", " << cA.imag() << "\n";
Complex<double> cB = 1.0; // Should print "1.0, 0" but prints garbage
std::cout<< "cB=" << cB.real() << ", " << cB.imag() << "\n";
Complex<int> cC = 1;
std::cout<< "cC=" << cC.real() << ", " << cC.imag() << "\n";
return 0;
}
Example output:
Complex: Default constructor cA=0, 0
Complex: Constructing from assignement! cB=6.91942e-310, 0
Complex: Constructing from assignement! cC=4199661, 0
The code on CompilerExplorer.
| Complex(T real) : re{re} { // should be re{real}, but why re{re} is not 0?
If you provide an initializer for a member explicitly in the constructor, then this initializer replaces the default member initializer. The default member initializer is in such a case not used at all.
To be clear: The default member initializers are not initializing the members prior to the constructor call. They just "fill up" the intializers for members not mentioned in the constructor's member initializer list.
In your case re{re} accesses an object outside it's lifetime (re), causing undefined behavior.
Also, as a side note: Complex<double> cB = 1.0; and Complex<int> cC = 1; are not assignments. Both are declarations with initialization. The = is not part of an assignment expression and doesn't call operator= as an assignment would. They are both copy-initialization, in contrast to Complex<double> cB(1.0); which is direct-initialization.
The constructor Complex(T real) used by either of these initializations is called a converting constructor.
|
70,513,923 | 70,515,115 | assertion fails: __is_complete_or_unbounded | While compiling HHVM, the code fails due to:
/usr/include/c++/10/type_traits:918:52: error: non-constant condition for static assertion
918 | static_assert(std::__is_complete_or_unbounded(__type_identity<_Tp>{}),
What does __is_complete_or_unbounded actually do/check?
The issue occurs while constructing an object whose last member variable is as follows:
value_type cell[0]
The constructor does not initialize this member, is this the problem? How would I initialize the value_type variable?
| In C++, an array cannot have zero size.
From Array declarators documentation:
If the expression is a constant expression, it shall have a value greater than zero.
|
70,514,422 | 70,526,080 | ADL warning: ambiguous conversion with boost operators and SFINAE | I'm trying to understand an ambiguous conversion warning during ADL for the following piece of code:
#include <boost/operators.hpp>
#include <boost/polygon/polygon.hpp>
class Scalar
: private boost::multiplicative< Scalar, double > {
public:
explicit Scalar( double val ) : mVal( val ) {}
Scalar &operator*=(double rhs) noexcept {
mVal *= rhs;
return (*this);
}
Scalar &operator/=(double rhs) noexcept {
mVal /= rhs;
return (*this);
}
private:
double mVal;
};
using Coordinate = int;
using Polygon = boost::polygon::polygon_with_holes_data<Coordinate>;
using Point = boost::polygon::polygon_traits<Polygon>::point_type;
template <class T, typename = std::enable_if_t<std::is_arithmetic_v<std::remove_reference_t<T>>>>
Point operator*(const Point &a, T b) noexcept {
return Point(a.x() * b, a.y() * b);
}
int main(int argc, char *argv[]){
Scalar a( 10 );
int b = 10;
Scalar a_times_b = a * b;
return 0;
}
I get the following warning for GCC 11.2:
<source>: In function 'int main(int, char**)':
<source>:33:28: warning: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second:
33 | Scalar a_times_b = a * b;
| ^
In file included from <source>:1:
/opt/compiler-explorer/libs/boost_1_78_0/boost/operators.hpp:268:1: note: candidate 1: 'Scalar boost::operators_impl::operator*(const Scalar&, const double&)'
268 | BOOST_BINARY_OPERATOR_COMMUTATIVE( multipliable, * )
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<source>:26:7: note: candidate 2: 'Point operator*(const Point&, T) [with T = int; <template-parameter-1-2> = void; Point = boost::polygon::point_data<int>]'
26 | Point operator*(const Point &a, T b) noexcept {
| ^~~~~~~~
<source>:33:12: warning: variable 'a_times_b' set but not used [-Wunused-but-set-variable]
33 | Scalar a_times_b = a * b;
|
See https://godbolt.org/z/qzfvjr86c. One way to fix this is to also inherit from boost::multiplicative< Scalar, int > and perhaps also define the operators *= and /= for int (which is technically unnecessary since we get implicit conversions from int to double).
My Confusion:
For the so called "first" there is a implicit built in int->double conversion. For the so called "second" is the compiler talking about some conversion from the Scalar class to Point? I'm not sure what this conversion chain looks like as I haven't defined any way for the Scalar class to be converted to a Point. Is there something I'm missing with the enable if? Is this some sort of bug in Boost or GCC?
| Your free operator* in the global namespace is too open. It actively assumes that Point is not constructible from Scalar, quod non:
no problem
vs using Boost Polygon's Point
You should restrict it more:
template <
typename P, typename S,
typename IsPoint = typename boost::polygon::is_point_concept<
typename boost::polygon::geometry_concept<P>::type>::type,
typename = std::enable_if_t<IsPoint::value and std::is_arithmetic_v<S>>>
auto operator*(P const& a, S const& b) noexcept {
return boost::polygon::construct<Point>(a.x() * b, a.y() * b);
}
I also suggest you
as shown, use the point traits to construct the point instead of assuming direct construction
don't put operator templates in global namespace (not shown)
use boost::polygon::scale that already exists and likely has more safeties and/or optimization (not shown)
Live Demo
Live On Compiler Explorer
#include <type_traits>
struct Scalar {
explicit Scalar(double val) : mVal(val) {}
private:
friend Scalar operator*(Scalar lhs, double rhs) noexcept {
lhs.mVal *= rhs;
return lhs;
}
double mVal;
};
#include <boost/polygon/polygon.hpp>
using Coordinate = int;
using Polygon = boost::polygon::polygon_with_holes_data<Coordinate>;
using Point = boost::polygon::polygon_traits<Polygon>::point_type;
template <
typename P, typename S,
typename IsPoint = typename boost::polygon::is_point_concept<
typename boost::polygon::geometry_concept<P>::type>::type,
typename = std::enable_if_t<IsPoint::value and std::is_arithmetic_v<S>>>
auto operator*(P const& a, S const& b) noexcept {
return boost::polygon::construct<Point>(a.x() * b, a.y() * b);
}
static_assert(std::is_arithmetic_v<double>);
static_assert(not std::is_arithmetic_v<Scalar>);
int main()
{
auto s = Scalar(10) * 10;
auto p = Point(10, 20) * 42;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.