I have written a program on 1st JAN 2023, and trying to run it in atom. But atom is not showing run option and even the sortcut f5 is not working.
I'm expecting the compilaion.
I have written a program on 1st JAN 2023, and trying to run it in atom. But atom is not showing run option and even the sortcut f5 is not working.
I'm expecting the compilaion.
Let us suggest I have a class called vec4. Its a template and could be uint8, float or int in most cases. Other cases are allowed but are less likely. The class looks like this:
template<class T>
class vec4 {
public:
vec4(){}
virtual ~vec4(){}
union {
struct {
T x,y,z,w;
};
struct {
T r,g,b,a;
};
};
};
This helps me think about a problem in different ways when writing code and allows me to do other cool things also and I rather enjoy the design pattern when ever applicable.
The problem is I would like to extend the class and add functions in the case it is a 32 bit float. That I can do. I would also like to extend the union for a further maths paradigm where the third members are T c,y,m,k.
I am finding it very difficult to find material on the subject.
For example, given the following:
// enum.h
enum class TestEnum: int {
ONE,
TWO,
THREE
};
// function.h
enum class TestEnum: int;
int TestFunction(TestEnum te = TestEnum::THREE);
// function.cpp
#include "enum.h"
#include "function.h"
int TestFunction(TestEnum te) {
return 5;
}
In my eyes this should not compile because in function.h, with TestEnum
only being forward declared, the compiler cannot know that TestEnum::THREE
(which is used as a default argument for TestFunction
) is a valid member of the enum. And yet it does.
If I forward declare a class, I cannot access its members, but with enums it seems I can. Why is that? And is this something "legal" as per the standard, or did it just happen to work because of the way the compilers I tried (clang and gcc) are implemented?
I want to run my c++ graphics program in termux. But, graphics.h is not install on my phone.
I tried to install graphics.h using command pkg install graphics
and pkg install graphics.h
in the same folder where my code was saved. But both command give me error that is E:unable to locate package
.
Have a look at following code:
#include <iostream>
#include <memory>
class A
{
public:
A()
{
std::cout << "A() \n";
}
~A()
{
std::cout << "~A() \n";
}
int a = 100;
};
class B
{
public:
B()
{
ptr.reset(new A());
std::cout << "B() \n";
std::cout << "pointer value" << ptr.get() << std::endl;
std::cout << ptr->a << std::endl;
}
~B()
{
std::cout << "~B() \n";
}
void print()
{
std::cout << "print() " << a << b << "\n";
std::cout << "pointer value" << ptr.get() << std::endl;
std::cout << ptr->a << std::endl;
}
private:
std::unique_ptr<A> ptr;
int a = 10;
int b = 5;
};
int main()
{
std::unique_ptr<B> p1(new B());
p1->~B();
p1->print();
return 0;
}
the output result:
A()
B()
pointer value010ECB60
100
~B()
~A()
print() 105
pointer value010ECB60
-572662307
~B()
~A()
The Question is:
a = 100
has been destroyed, but class B's member a = 10; b = 5
still exist, and it's value not changed, so class B's destructor can't be seen as a function, since it called class A's destructor, how to explain this?HEAP[Destructor.exe]: Invalid address specified to RtlValidateHeap( 00EA0000, 00EACE38 )
, because class B's destructor called first time so object A has been destroyed, this will destroy it twice?I add some print info to track workflow, but i still don't figure out how it worked when called the destructor explicitly.
Here is my simple code
#include <iostream>
#include <string>
using namespace std;
int main() {
string food = "Pizza";
string &meal = food;
string okay = "okay";
&meal = okay; // showing error in updating meal reference
cout << food << "\n"; // Outputs should be Pizza
cout << meal << "\n"; // Outputs Should be okay
return 0;
}
I reference have a meal variable to the same location as food so now the meal value is Pizza but now I want to update the meal reference location to okay such that the food value is still Pizza but the meal updated to okay.
is there any way to update the reference variable to another variable?
I have int a,b how can I have int ab ?
for example
I have :
int a=5 , b=4 ;
I want :
int c=54 ;
This question body does not meet our quality standards. Please make sure that it completely describes your problem - including what you have already tried - and is written using proper grammar. ):
Im looking to take my vector and depending on the p_room[] choosen give a special dialog and crerate a array for that specific vector. for example if the user goes from startingRoom to startingEast then to eastlvl1 i want a special dialog for the eastlvl1 i tried if statments but they appear when the app is first ran. i want a way to create path specific dialog along with creating arrays along that path so if they reach a certain point and find an object i can create an array and store the object. but i dont want the user to always have an inventory i only want it to exist once they find an object if they find
#include <iostream>
#include <vector>
#include <string>
#include "Room.h"
using namespace std;
class Program{
public:
Program();
~Program();
void setUpRooms();
void Run();
private:
int createRoom(string name, string description);
void handleUserInput();
Room* p_ptrCurrentRooms;
vector<Room*> p_rooms;
bool p_done;
Room customRoom();
};
Program::Program(){
p_ptrCurrentRooms = nullptr;
setUpRooms();
p_done = false;
}
void Program::Run() {
string status = "";
while (!p_done){
p_ptrCurrentRooms->outputRoomInfo();
handleUserInput() ;
Menu::Pause();
}
}
void Program::setUpRooms() {
int spawn = createRoom("your house","theres a flash of light");
int startingRoom = createRoom("Town Center","You appear in a mysteries town");
int startingNorth = createRoom("Capital","You enter the capital");
int startingSouth = createRoom("Dense Forest","You enter a forest where light can barely reach the ground");
int startingEast = createRoom("Ocean","You have reached an ocean");
int startingWest = createRoom("Town","you have traveled deeper into town");
int northLevel1 = createRoom("Castle","you find a massive castle");
int northSthLevel1 = createRoom("Town center","Back at the town center but it looks different from before, yet you are unsure how");
int northEstLevel1 = createRoom("Ocean","You have reached a port");
int northWstLevel1 = createRoom("Slums","A dirtier and much more unpleasant place compared to previous surroundings ");
int northLvl2 = createRoom("Castle","you reach the castle gate and are stopped by guards, you explain your situation. They look you over and can clearly tell you arent"
" from there at least and allow you to pass with an escort. continue north to proceed with your escort. ");
//northSthLevel1
int northEstLvl2 = createRoom("Castle","You walk the castle wall, it is miles long and even taller. made from a hard stone you've never seen before");
int northWstLvl2 = createRoom("Castle","You walk the castle wall, it is miles long and even taller. made from a hard stone you've never seen before");
int southLevel1 = createRoom("Dense Forest","You travel deeper into the the dense forest, nothing interesting found");
int southNorthLevel1 = createRoom("Dense forest","The forest was so dark and dense when you entered... are you lost?");
int southEstLevel1 = createRoom("Dense Forest","just more forest nothing interesting.");
int southWstLevel1 = createRoom("Dense Forest","just more forest nothing interesting.");
int southLevel2 = createRoom("Dense Forest","You travel deeper into the the dense forest, nothing interesting found");
int southNrthLvl2 = createRoom("Dense Forest","You reach the edge of the forest, you've made it out.");
int southEstLvl2 = createRoom("Dense Forest","just more forest nothing interesting. its starting to get dark");
int southWstLvl2 = createRoom("Dense Forest","just more forest nothing interesting. its starting to get dark");
int eastLvl1 = createRoom("Ocean","You have entered the ocean continue east to swim further into ocean");
int eastNrthLvl1 = createRoom("Port","you found a port, continue east from here to board a ship");
int eastSthlvl1 = createRoom("Market","you find a market that sells a variety of the days catches");
//use northsthlvl1
int eastlvl2 = createRoom("Ocean","you have started your swim into the ocean");
int eastNrthLvl2 = createRoom("Port","you continue along the port, continue east from here to board a ship");
int eastSthlvl2 = createRoom("Market","you continue along the market that sells a variety of the days catches");
//use northSouthLevel1
int westLvl1 = createRoom("Town","The path you where walking opens into a large square with shops spread throughout the square");
int westNrthLvl1 = createRoom("Town","You come across a building marked Guild. by its stature maybe it has some importance or information. continue North to enter");
int westSthLvl1 = createRoom("Town","Hunters Lodge... wonder what information they may carry");
// use northSthLevel1
int westLvl2 = createRoom("Town square","You've entered teh center of the town square you are surrounded by shops. continue North, South, West to enter a shop and east to back up");
int westNrthLvl2 = createRoom("Guild","you've entered the guild the building seems bigger on the inside, it seems over whelming. - Continue North, West, or East to venture through guild and south to exit");
int westSthLvl2 = createRoom("Hunters Lodge","you have entered the lodge there are mounts of unknown animals on the wall. - Continue South, West, East to explore lodge and North to exit");
//use northSthLevel1
// NORTH, SOUTH, EAST, WEST
p_rooms[spawn]->setNeighbors( p_rooms[startingRoom],p_rooms[startingRoom], p_rooms[startingRoom], p_rooms[startingRoom]);
p_rooms[startingRoom]->setNeighbors(p_rooms[startingNorth],p_rooms[startingSouth],p_rooms[startingEast], p_rooms[startingWest]);
p_rooms[startingNorth]->setNeighbors(p_rooms[northLevel1], p_rooms[northSthLevel1], p_rooms[northEstLevel1], p_rooms[northWstLevel1]);
p_rooms[startingSouth]->setNeighbors(p_rooms[southNorthLevel1],p_rooms[southLevel1],p_rooms[southEstLevel1],p_rooms[southWstLevel1]);
p_rooms[startingEast]->setNeighbors(p_rooms[eastNrthLvl1],p_rooms[eastSthlvl1],p_rooms[eastLvl1],p_rooms[northSthLevel1]);
p_rooms[startingWest]->setNeighbors(p_rooms[westNrthLvl1], p_rooms[westSthLvl1], p_rooms[northSthLevel1], p_rooms[westLvl1]);
p_rooms[northLevel1]->setNeighbors(p_rooms[northLvl2],p_rooms[northSthLevel1], p_rooms[northEstLvl2], p_rooms[northWstLvl2]);
p_rooms[southLevel1]->setNeighbors(p_rooms[southNrthLvl2], p_rooms[southLevel2], p_rooms[southEstLvl2], p_rooms[southWstLvl2]);
p_rooms[eastLvl1]->setNeighbors(p_rooms[eastNrthLvl2], p_rooms[eastSthlvl2], p_rooms[eastlvl2], p_rooms[northSthLevel1]);
p_rooms[westLvl1]->setNeighbors(p_rooms[westNrthLvl2], p_rooms[westSthLvl2], p_rooms[northSthLevel1], p_rooms[westLvl2]);
p_ptrCurrentRooms = p_rooms[spawn];
}
int Program::createRoom(string name, string description){
int index = p_rooms.size();
Room* room = new Room;
room->setUp(name, description);
p_rooms.push_back(room);
return index;
}
void Program::handleUserInput(){
string userIn;
userIn = Menu::GetStringLine("What would you like to do next");
if(StringUtil::ToLower(userIn) == "north" || StringUtil::ToLower(userIn) == "n"){
if(p_ptrCurrentRooms->canGo(NORTH)){
cout << "you went North";
p_ptrCurrentRooms = p_ptrCurrentRooms->ptrNeighborNorth;
}else{
cout << "you cant go north";
}
}
else if(StringUtil::ToLower(userIn) == "south" || StringUtil::ToLower(userIn) == "s"){
if(p_ptrCurrentRooms->canGo(SOUTH)){
cout << "you went South";
p_ptrCurrentRooms = p_ptrCurrentRooms->ptrNeighborSouth;
}else{
cout << "you cant go South";
}
}
else if(StringUtil::ToLower(userIn) == "east" || StringUtil::ToLower(userIn) == "e"){
if(p_ptrCurrentRooms->canGo(EAST)){
cout << "you went East";
p_ptrCurrentRooms = p_ptrCurrentRooms->ptrNeighborEast;
}else{
cout << "you cant go East";
}
}
else if(StringUtil::ToLower(userIn) == "west" ||StringUtil::ToLower(userIn) == "w" ){
if(p_ptrCurrentRooms->canGo(WEST)){
cout<< "you went west";
p_ptrCurrentRooms = p_ptrCurrentRooms->ptrNeighborWest;
}else{
cout<< "you cant go west";
}
} else{
cout<< "Unknown command";
}
}
Program::~Program(){
for(auto ptrRoom : p_rooms){
if(ptrRoom!= nullptr){
delete ptrRoom;
}
}
}
ive tried p_room.at() or declaring the specific room in if staments but all that does is print the message first in the console
int main()
{
char j[] = "abc";
print(j);
}
When I define print
like this:
void print(const char *cp)
{
if (cp)
{
while (*cp)
{
int i = *cp;
cout << *cp;
// cout << *cp << endl;
cp++;
}
}
}
The console is something like this (I can not copy the result property, so I use a screenshot) The %
like character is quite expected
However, when I put the endl
the wired %
character disappear
void print(const char *cp)
{
if (cp)
{
while (*cp)
{
int i = *cp;
// cout << *cp;
cout << *cp << endl;
cp++;
}
}
}
Could anyone help explain what happen?
I do not think %
is not part of the prompt
I change my prompt the a text 'a', and the %
still present
I'm trying to build a string or character to send to a function.
error:
In member function 'void RTSSHOW::RTS_Init()':
Marlin/src/lcd/e3v2/creality/LCD_RTS.cpp:383:37: warning: '%f' directive writing between 3 and 317 bytes into a region of size 0 [-Wformat-overflow=]
383 | sprintf_P((char*)mstr, PSTR("%s %f"), mstr, z_values[x][y] * 1000);
Short code summary:
auto mstr = (char*)""; // here is the string I'm trying to build
sprintf_P((char*)mstr, PSTR("%s %f"), mstr, z_values[x][y] * 1000);
sprintf_P((char*)mstr, PSTR("%s %s"), mstr, "\n");
RTS_SndData((char*)mstr, AUTO_BED_LEVEL_MESH_VP);
here is my code pastebin: https://pastebin.com/xrk2GJsh
I'm not fluent in C++ and building a string is not the same as in PHP which I am used to.
I've tried various string and char declarations, but cannot seem to get it.
I need to centrally accumulate certain entity creations in my program into a container and I want to use the efficiency of std::move with a move constructor to aggregate all entities created anwhere in the program into one container witout extra copying or instance allocations. Unfortunately using the most popular std::vector container brings with it vector internal management overhead ( or is that compiler implementation dependent??)
For example
class Item {
public :
static int Count;
int ID;
Item() : ID(Count++)
{ cout<<" Item CREATED - ID:"<<ID<<endl; }
Item(const Item &itm) : ID(Count++)
{ cout<<" Item COPY CREATED - (ID:"<<ID<<") <= (ID:"<<itm.ID<<")\n"; }
Item(const Item &&itm) : ID(Count++)
{ cout<<" Item MOVE CREATED - (ID:"<<ID<<") <= (ID:"<<itm.ID<<")\n"; }
~Item() { cout<<" Item DELETED - (ID:"<<ID<<") \n"; }
};
int Item::Count = 0;
void VectorOfItemTest() {
std::vector<Item> ItemVec;
for(int idx=0; idx<3; idx++) {
std::cout<<" { loop "<<idx<<std::endl;
Item itemInst;
ItemVec.push_back(std::move(itemInst));
std::cout<<" } "<<idx<<std::endl<<std::endl;
}
}
produces output :
-----------------------------
{ loop 0
Item CREATED - ID:0
Item MOVE CREATED - (ID:1) <= (ID:0)
} 0
Item DELETED - (ID:0)
{ loop 1
Item CREATED - ID:2
Item MOVE CREATED - (ID:3) <= (ID:2)
Item COPY CREATED - (ID:4) <= (ID:1)
Item DELETED - (ID:1)
} 1
Item DELETED - (ID:2)
{ loop 2
Item CREATED - ID:5
Item MOVE CREATED - (ID:6) <= (ID:5)
Item COPY CREATED - (ID:7) <= (ID:4)
Item COPY CREATED - (ID:8) <= (ID:3)
Item DELETED - (ID:4)
Item DELETED - (ID:3)
} 2
Item DELETED - (ID:5)
Item DELETED - (ID:7)
Item DELETED - (ID:8)
Item DELETED - (ID:6)
Is it possible to avoid the extra copy-s that causes matching delete-s inside the for loop?
Is there a container (or can we use std::vector in any way) where we get all loop outputs looking as follows ?
{ loop X
Item CREATED - ID:X
Item MOVE CREATED - (ID:X+1) <= (ID:X)
} X
Item DELETED - (ID:X)
I have looked at Why std::move is required to invoke move assign operator of std::vector Why does std::move copy contents for a rvalue or const lvalue function argument? and a few others here but its still not clear how I can use std::vector (or other containers) efficiently with using std::move.
I found a rejected question Hard time understanding object lifetime, copy, move constructor asking close to what I am referring to here I guess.
I am trying to read entries of my csv file into an entries vector whose data type is object OrderBookEntry, this is an object that stores the tokenized variables from the csv line which itself is converted through the function tokenise. My problem is that my csv file has around a million lines and it takes over 30 seconds to load, how can I reduce this?
This is my code that actually reads lines from the file and converts them into entries.
'''
std::vector<OrderBookEntry> CSVReader::readCSV(std::string csvFilename)
{
std::vector<OrderBookEntry> entries;
std::ifstream csvFile{csvFilename};
std::string line;
if (csvFile.is_open())
{
while(std::getline(csvFile, line))
{
try {
OrderBookEntry obe = stringsToOBE(tokenise(line, ','));
entries.push_back(obe);
//std::cout << "pushing entry" << std::endl;
}catch(const std::exception& e)
{
//std::cout << "CSVReader::readCSV bad data" << std::endl;
}
}// end of while
}
std::cout << "CSVReader::readCSV read " << entries.size() << " entries" <<
std::endl;
return entries;
}
''' This is the part of my code that tokenises the read line '''
std::vector<std::string> CSVReader::tokenise(std::string csvLine, char separator)
{
std::vector<std::string> tokens;
signed int start, end;
std::string token;
start = csvLine.find_first_not_of(separator, 0);
do{
end = csvLine.find_first_of(separator, start);
if (start == csvLine.length() || start == end) break;
if (end >= 0) token = csvLine.substr(start, end - start);
else token = csvLine.substr(start, csvLine.length() - start);
tokens.push_back(token);
start = end + 1;
}while(end > 0);
return tokens;
}
''' this is the part of my code that converts the tokens into a suitable object to work with '''
OrderBookEntry CSVReader::stringsToOBE(std::vector<std::string> tokens)
{
double price, amount;
if (tokens.size() != 5) // bad
{
//std::cout << "Bad line " << std::endl;
throw std::exception{};
}
// we have 5 tokens
try {
price = std::stod(tokens[3]);
amount = std::stod(tokens[4]);
}catch(const std::exception& e){
std::cout << "Bad float! " << tokens[3]<< std::endl;
std::cout << "Bad float! " << tokens[4]<< std::endl;
throw;
}
OrderBookEntry obe{price,
amount,
tokens[0],
tokens[1],
OrderBookEntry::stringToOrderBookType(tokens[2])};
return obe;
}
'''
I have this code and it doesn't compiled. It has an error
cannot assign to variable 'value' with const-qualified type 'const int &' value = 5;
#include <vector>
#include <set>
int main() {
std::vector<std::set<int>> data;
for (auto it = data.begin(); it != data.end(); ++it) {
auto& inner = *it;
for (auto& value: inner) {
value = 5;
}
}
return 0;
}
I thought inner
is std::set<int>&
and value
would be int&
in this case. Could someone explain this case? Thanks
I'm looking for a creative way to abide by the framework of my current project. I'm kinda stuck with it, here is the situation.
The developer's code needs to be always enclosed within an if statement because there is an external control by the framework that allows the user to skip or execute a code/procedure.
if (condition) {
int s;
std::string myprocedurename;
}
instead of doing that always, I would like to explore a way to implement a class that will in effect handle the if() condition requirement so that the user code for procedures will look something like:
void myProcedure
{
ConditionalExecuteContext cxt;
int s;
std::string myprocedurename;
}
I'm trying to "emulate" the if() condition effect in the ConditionalExecuteContext class but to no success. Maybe someone will have a better idea? If only I can change the framework and implement something better than the if statement I would, but since I arrived late to the party we're kind stuck with it. :)
I understand how to call a method not encased in a class using offsets like this through DLL injection:
test.dll
#define TEST_FUNCTION_OFFSET 0x109010 // random offset
typedef __int64(__cdecl * _test)(void);
_test test;
DWORD WINAPI MainThread(LPVOID param) {
std::uintptr_t base_address = reinterpret_cast<uintptr_t>(GetModuleHandle(NULL));
test = (_test)(base_address + TEST_FUNCTION_OFFSET);
test();
}
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
switch (ul_reason_for_call) {
case DLL_PROCESS_ATTACH:
CreateThread(NULL, NULL, MainThread, hModule, NULL, NULL);
break;
case DLL_PROCESS_DETACH:
break;
} return TRUE;
}
main.cpp
#include <iostream>
#include "example.h"
void test() {
std::cout << "Test" << std::endl;
}
int main() {
example ex;
ex.incrementID();
return 0;
}
example.h
class example {
private:
int _id = 1234;
public:
void incrementID() { _id++; };
};
But how would I go about calling incrementID()
on the ex
object in main()
if I have the addresses of example::incrementID()
and ex
?
My general Idea is to form an event driven code flow in my Arduino projects. I had nice experience with events in C# but since Arduino uses C++ and doesn't have required base (so far as I know) I can't use this technique natively. The general idea is to create a class Event which supports the following API:
class Event {
void Add(function f);
void Remove(function f);
};
The event class will be than managed with the help of another object which will call or 'unwrap' all the events in a loop function - the part of the program that executes on the Arduino board in a loop.
now the problem with this idea is that it requires memory allocation (vector) to add and store these functions, it may be acceptable for machines with large amount of RAM, but for small ones it can be not efficient enough, for Arduino it can take more time also so the time managed processes can be affected.
I am not sure if it is possible or there is another solution, but my idea is to use some 'template-magic' and tune all the functions to the events in the setup function, which runs once as an initialization before the loop executes. By this I want to avoid allocations and make these events immutable (only after all the functions are tuned) but this seems not possible because to declare an array we need to set its size but in this case the size would be discovered only in the end.
The code I would like to clean, if possible, looks like this:
int button_pin1 = 1;
int button_pin2 = 2;
int button_pin3 = 3;
int button_pin4 = 4;
int button_pin5 = 5;
int button_pin6 = 6;
int button_pin7 = 7;
int button_pin8 = 8;
int button_pin9 = 9;
int button_pin10 = 10;
void blinkled(int button_pin){
if (button_pin % 2 == 0)
digitalWrite(LED_BUILTIN, HIGH);
}
void printToDisplay(int button_pin);
void doImportantStuff(int button_pin);
void implementSuperNatural(int button_pin);
void setup() {
for(int i = button_pin1; i= < button_pin10; i++)
pinMode(i, INPUT);
}
void loop() {
if (digitalRead(button_pin1){
blinkLed(button_pin1);
})
if (digitalRead(button_pin2){
blinkLed(button_pin2);
printToDisplay(button_pin2);
})
if (digitalRead(button_pin3){
printToDisplay(button_pin3);
doImportantStuff(button_pin3);
implementSuperNatural(button_pin3);
})
// write if statements for any button that was pressed with any combination of functions above ...
}
after the cleanup I would like it to look like this: `
void blinkled(int button_pin){
if (button_pin % 2 == 0)
digitalWrite(LED_BUILTIN, HIGH);
}
void printToDisplay(int button_pin);
void doImportantStuff(int button_pin);
void implementSuperNatural(int button_pin);
//Button will be a class that reperesents a real button.
Button buttons[] = Button::from_pins(1,2,3,4,5,6,7,8,9,10);
void setup() {
for(int i = 0; i < sizeof(buttons) / sizeof(buttons[0]; i++))
buttons[i].activate();
buttons[0].onClick += printToDisplay;
buttons[3].onClick += {doImportantStuff, printToDisplay}; // the += operator resembles the 'add' method in the API
buttons[10].onClick += {blinkLed, implementSuperNatural};
if constexpr (//some condition){
buttons[3].onClick += printToDisplay;
buttons[10].onClick -= blinkled; // the -= opreator resembles the remove method in the API
}
void loop() {
EventSchduler::run();
}
`
This 'clean' code written above is not formatted well but I hope it makes the idea clearer.
Maybe the whole Idea is completely wrong, and many will say it's a waste or the question is unclear, or the technique is simply bad. I just want to get people's opinions and learn.
How can we efficiently load the data from an incremental CSV file without reading the whole file repetitively?
I have used the timestamp information from the given file to load the data in every 5 minutes but in case the timestamp information is not available how can we make it work?
I have two classes (actually four, but they're not required for this). Let's call them A, and B. I am trying to declare class B as a member in class A. My problem is, I need access to a member function inside of class A from class B, but it doesn't make sense for these two classes to be inherited from each other.
Here are the two classes:
Class A:
#include "B.h"
class A {
B test;
public:
A() : test {this} {}
};
Class B:
#include "A.h"
class B: public Alert {
A* test;
public:
B() = default;
B(A* testIn) : test{ testIn } {}
// member functions
};
I am using Visual Studio Community Edition 2022 (64-Bit). My C++ version is C++11.
The compiler error I keep getting is "testIn undeclared identifier." This makes no sense to me, as I feel I have declared it.
I understand that making one of the classes a child of the other would allow the child class to access the public and protected members of the parent class.
The thing is, in this instance, it makes no sense for them to inherit from each other. I only need access to a function inside of class A from class B, as class A inherits from another class. I am trying to write a library, and want class A to be the class that would be used by other people. It wouldn't make any sense having class B be the class to be used in the final program. Which is why I didn't want to inherit the one from the other.
I appreciate your time for looking at my question.
Update: John's solution posted below in his own submission is correct for my original question. I am just an idiot and forgot to include that Class A also inherits from another class.
Class A would look like the following:
#include "AnotherClass.h"
#include "B.h"
class A: AnotherClass {
B test;
public:
A() : test {this} {}
};
Terribly sorry about my confusion. I definitely messed up.
constexpr base::StringPiece StripLambda(base::StringPiece shader) {
// Must contain at least "[]() {}".
DCHECK_EQ(shader.substr(0, 6), "[]() {");
DCHECK_EQ(shader.back(), '}');
shader.remove_prefix(6);
shader.remove_suffix(1);
return shader;
}
chromium94/src/components/viz/service/display/shader.cc:29:23: in 'constexpr' expansion of 'shader.base::BasicStringPiece::remove_prefix(6)' chromium94/src/base/check_op.h:157:41: error: 'constexpr logging::CheckOpResult logging::CheckLEImpl(T, U, const char*) [with T = unsigned int; U = unsigned int; typename std::enable_if<(std::is_fundamental<_Tp>::value && std::is_fundamental::value), int>::type = 0]' called in a constant expression
chromium94/src/base/check_op.h:184:38: error: call to non-'constexpr' function 'logging::CheckOpResult::CheckOpResult(const char*, char*, char*)'
chromium94/src/base/check_op.h:157:41: error: 'constexpr logging::CheckOpResult logging::CheckLEImpl(T, U, const char*) [with T = unsigned int; U = unsigned int; typename std::enable_if<(std::is_fundamental<_Tp>::value && std::is_fundamental::value), int>::type = 0]' called in a constant expression
Can anyone help with work around solution?
Can anyone help with work around solution?
From the book "The C++ Programming Language - Fourth Edition" on the following pages:
p. 501:
For example:
struct B {B(int); /* ... */ };
struct BB:B {/* ... */ };
struct BBB: BB {
BBB(int i) : B(i) {}; // error: trying to initialize base's base
// ...
};
vs.
p. 491:
But why is the following code allowed, then?
struct Y : X {
X m {0};
Y(int a) : X{a}, m{a} {};
Y() : X{0} {};
}
This program gives the output for example "10-->55". I want the sum of the numbers set by step for example "1-->1 2-->3 3-->6....." so on. How can I archive this?
One of my projects uses C++11 std::array
for fixed-sized array types, and so I'm trying to specialise Rcpp::as()
for convenient conversion from SEXP
to these types. Since this requires partial specialisation, I've followed the Exporter
route as outlined in Rcpp-extending:
#include <RcppCommon.h>
#include <array>
namespace Rcpp {
namespace traits {
// Partial specialisation to allow as<array<T,D>>(...)
template <typename ElementType, int Dimensionality>
class Exporter<std::array<ElementType,Dimensionality>>
{
private:
std::array<ElementType,Dimensionality> value;
public:
Exporter (SEXP x)
{
std::vector<ElementType> vec = as<std::vector<ElementType>>(x);
if (vec.size() != Dimensionality)
throw Rcpp::exception("Array does not have the expected number of elements");
for (int i=0; i<Dimensionality; i++)
value[i] = vec[i];
}
std::array<ElementType,Dimensionality> get () { return value; }
};
} // traits namespace
} // Rcppnamespace
#include <Rcpp.h>
Other code within the package can then do, for example,
std::array<double,3> arr = Rcpp::as<std::array<double,3>>(vec);
I've bundled this up into a minimal package for example purposes; the "real" application is here.
The problem is that this approach compiles and works fine for me locally (macOS, clang), but gcc doesn't like it. The output from a GitHub CI action on the minimal package is below.
* installing *source* package ‘Rcpp.asArray’ ...
** using staged installation
** libs
g++ -std=gnu++11 -I"/opt/R/4.2.2/lib/R/include" -DNDEBUG -I'/home/runner/work/_temp/Library/Rcpp/include' -I/usr/local/include -fpic -g -O2 -c main.cpp -o main.o
In file included from /home/runner/work/_temp/Library/Rcpp/include/Rcpp/as.h:25,
from /home/runner/work/_temp/Library/Rcpp/include/RcppCommon.h:169,
from array.h:4,
from main.cpp:1:
/home/runner/work/_temp/Library/Rcpp/include/Rcpp/internal/Exporter.h: In instantiation of ‘Rcpp::traits::Exporter<T>::Exporter(SEXP) [with T = std::array<double, 3>; SEXP = SEXPREC*]’:
/home/runner/work/_temp/Library/Rcpp/include/Rcpp/as.h:87:41: required from ‘T Rcpp::internal::as(SEXP, Rcpp::traits::r_type_generic_tag) [with T = std::array<double, 3>; SEXP = SEXPREC*]’
/home/runner/work/_temp/Library/Rcpp/include/Rcpp/as.h:152:31: required from ‘T Rcpp::as(SEXP) [with T = std::array<double, 3>; SEXP = SEXPREC*]’
main.cpp:8:62: required from here
/home/runner/work/_temp/Library/Rcpp/include/Rcpp/internal/Exporter.h:31:42: error: no matching function for call to ‘std::array<double, 3>::array(SEXPREC*&)’
31 | Exporter( SEXP x ) : t(x){}
| ^~~~
In file included from /usr/include/c++/11/tuple:39,
from /usr/include/c++/11/bits/hashtable_policy.h:34,
from /usr/include/c++/11/bits/hashtable.h:35,
from /usr/include/c++/11/unordered_map:46,
from /home/runner/work/_temp/Library/Rcpp/include/Rcpp/platform/compiler.h:153,
from /home/runner/work/_temp/Library/Rcpp/include/Rcpp/r/headers.h:62,
from /home/runner/work/_temp/Library/Rcpp/include/RcppCommon.h:30,
from array.h:4,
from main.cpp:1:
/usr/include/c++/11/array:95:12: note: candidate: ‘std::array<double, 3>::array()’
95 | struct array
| ^~~~~
/usr/include/c++/11/array:95:12: note: candidate expects 0 arguments, 1 provided
/usr/include/c++/11/array:95:12: note: candidate: ‘constexpr std::array<double, 3>::array(const std::array<double, 3>&)’
/usr/include/c++/11/array:95:12: note: no known conversion for argument 1 from ‘SEXP’ {aka ‘SEXPREC*’} to ‘const std::array<double, 3>&’
/usr/include/c++/11/array:95:12: note: candidate: ‘constexpr std::array<double, 3>::array(std::array<double, 3>&&)’
/usr/include/c++/11/array:95:12: note: no known conversion for argument 1 from ‘SEXP’ {aka ‘SEXPREC*’} to ‘std::array<double, 3>&&’
make: *** [/opt/R/4.2.2/lib/R/etc/Makeconf:178: main.o] Error 1
ERROR: compilation failed for package ‘Rcpp.asArray’
* removing ‘/home/runner/work/Rcpp.asArray/Rcpp.asArray/Rcpp.asArray.Rcheck/Rcpp.asArray’
I don't know the internals of Rcpp
well enough to be sure, but it looks like the default implementation of Exporter
is being used in preference to the custom one, and failing because there is no std::array
constructor for SEXP
, which would involve intrusive modification.
Can anyone suggest a way to resolve this, please?
I am c + + novice, I want to ask this code, a + b executed once or twice, with what method to verify?
double num3 = [](double a, double b)->decltype(a + b) { return a + b; }(1.2, 2.1);
So i am learning about C++ special members in details.
i was fiddling with codes and trying different ways, then came across to this:
#include <iostream>
#include <string>
using namespace std;
class Example5 {
public:
string* ptr;
public:
Example5 (const string& str) : ptr(new string(str)) {}
~Example5 () {delete ptr;}
// copy constructor:
Example5 (const Example5& x) : ptr(x.ptr) {}
};
int main () {
Example5 foo ("Example");
Example5 bar (foo);
cout << foo.ptr << endl << bar.ptr;
return 0;
}
this code showing a shallow copy of object with the expected result :
0x505348
0x505348
while this code does not appear to preform a shallow copy
// copy constructor: deep copy
#include <iostream>
#include <string>
using namespace std;
class Example5 {
public:
string* ptr;
public:
Example5 (const string& str) : ptr(new string(str)) {}
~Example5 () {delete ptr;}
// copy constructor:
Example5 (const Example5& x) : ptr((*this).ptr) {}
};
int main () {
Example5 foo ("Example");
Example5 bar (foo);
cout << foo.ptr << endl << bar.ptr;
return 0;
}
with these results :
0x505348
0x505278
isn't *this
just points to the object and it's members ??
i was expecting same outcome.
I have a string that contains only A, B, C, D. I need to remove all odd-appeared characters in this string. For example if string is "ABBBCA" it will turn into "BA" (first "A" removed because it was first time "A" appeared, then first and third "B" removed, and "C" also, because it was first time it appeared). I'm beginner in coding, so i'm sorry if this question is too simple or something.
I have tried something like this:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string firstchars = "ABBBCA";
for (int o = 0; o < firstchars.length(); o ++) {
firstchars.erase(o,1);
}
But it just erases every odd element in string, not every odd "A", "B", "C" and "D". And i have "BBA" as output.
I am getting a linking error with my two C++ files as seen below. Compile error
It compiles up to the point of two object files then fails on linking.
Below is my code, I commented out most of main in order to isolate the issue.
I am using the boost/JSON library. The duplicates are all from the boost JSON library.
The JSONParser file is going to take in a JSON object and turn it to a C++ object but I don't think anything to do with the actual code is the issue. Just either a library or header file issue.
main.cpp
#include "JSONParser.hpp"
/*
#include <boost/beast/core.hpp>
#include <boost/beast.hpp>
#include <boost/beast/ssl.hpp>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <iostream>
#include <string>
#include <thread>
namespace net = boost::asio;
namespace beast = boost::beast;
using namespace boost::beast;
using namespace boost::beast::websocket;
*/
int main (void) {
//net::io_context ioc;
//tcp_stream sock(ioc);
//net::ssl::context ctx(net::ssl::context::tlsv12);
}
JSONParser.hpp
#ifndef JSONPARSER_H
#define JSONPARSER_H
#define BOOST_JSON_STACK_BUFFER_SIZE 1024
#include <boost/json/src.hpp>
class candlestick{
private:
double openPrice;
double closePrice;
double priceHigh;
double priceLow;
double baseVolume;
double quoteVolume;
bool isClosed;
public:
candlestick (double oP, double cP, double pH, double pL, double bV, double qV, bool iC);
void setopenPrice(double p) {
openPrice = p;
}
double getopenPrice(void) {
return openPrice;
}
void setclosePrice(double p) {
closePrice = p;
}
double getclosePrice(void) {
return closePrice;
}
void setpriceHigh(double p) {
priceHigh = p;
}
double getpriceHigh(void) {
return priceHigh;
}
void setpriceLow(double p) {
priceLow = p;
}
double getpriceLow(void) {
return priceLow;
}
void setbaseVolume(double v) {
baseVolume = v;
}
double getbaseVolume(void) {
return baseVolume;
}
void setquoteVolume(double v) {
quoteVolume = v;
}
double getquoteVolume(void) {
return quoteVolume;
}
void setClosed(bool c) {
isClosed = c;
}
bool getClosed(void) {
return isClosed;
}
};
candlestick::candlestick (double oP, double cP, double pH, double pL, double bV, double qV, bool iC) {
openPrice = oP;
closePrice = cP;
priceHigh = pH;
priceLow = pL;
baseVolume = bV;
quoteVolume = qV;
isClosed = iC;
};
candlestick createCandlestickObject ();
#endif
JSONParser.cpp
#include "JSONParser.hpp"
#include <iostream>
#include <sstream>
#include <string>
candlestick createCandlestickObject () {
candlestick c (2, 2, 2, 2, 2, 2, true);
return c;
}
By commenting out the #include "JSONParser.hpp" out of main, I was able to remove the error, therefore definitely a linking issue.
I wrote this code: Code for example for test 2 3 it should output 0.66666666 but it outputs 0.66666667 So how can i treat that rounding in the end of my double value?
Consider the following code (Godbolt):
#include <tuple>
#include <type_traits> // std::false_type, std::true_type
template <typename t_tuple, auto t_size = std::tuple_size_v<t_tuple>>
struct test : std::false_type {};
template <typename t_tuple>
struct test<t_tuple, 0> : std::true_type {};
int main(int argc, char **argv)
{
static_assert(test<std::tuple<>>::value);
return 0;
}
Clang and some other compilers accept the code but in GCC and ICC the static assertion fails. Either changing the type of t_size
from auto
to std::size_t
or casting the zero in the specialisation to std::size_t
alleviates the issue. What I would like to know is:
int
instead of std::size_t
when setting the type of the second template parameter to auto
? Obviously (?) the types do not match (since the type of std::tuple_size_v
is std::size_t
) but I was expecting the compiler to at least warn me about something.auto
with non-type template parameters?(I checked this question but it had to do with const
/volatile
.)
I have an header file header:
#ifndef __DATABASE_HELPER_H__
#define __DATABASE_HELPER_H__
class DatabaseHelper{
public:
static QJsonDocument* database;
DatabaseHelper();
static Card* selectJSonCard(std::string cardCode);
static void testFunctions();
static bool isLeader(std::string cardCode);
};
#endif
QJsonDocument* DatabaseHelper::database = &(QJsonDocument());
void DatabaseHelper::testFunctions(){
std::cout << "test" << std::endl;
}
//and so on for the others
Now I need it to be included from two different file. With one is fine, it compiles, but 2 gives me this error:
[ERROR] ./models/../utils/database_helper.h:38:16: error: redefinition of ‘QJsonDocument* DatabaseHelper::database’
38 | QJsonDocument* DatabaseHelper::database = &(QJsonDocument());
| ^~~~~~~~~~~~~~
./utils/database_helper.h:38:16: note: ‘QJsonDocument* DatabaseHelper::database’ previously declared here
38 | QJsonDocument* DatabaseHelper::database = &(QJsonDocument());
| ^~~~~~~~~~~~~~
./models/../utils/database_helper.h:114:6: error: redefinition of ‘static void DatabaseHelper::testFunctions()’
114 | void DatabaseHelper::testFunctions(){
| ^~~~~~~~~~~~~~
./utils/database_helper.h:114:6: note: ‘static void DatabaseHelper::testFunctions()’ previously defined here
114 | void DatabaseHelper::testFunctions(){
| ^~~~~~~~~~~~~~
Where the first file including this is in folder ./models/ and the other one in ./ . My goal is to be able to access the static function from every file in which I include the header, and have just one istance of the QJsonDocument variable "database". Am I missing something? Is there a way to do it?
I get an |65|error: no match for 'operator<<' (operand types are 'std::basic_ostream' and '__gnu_cxx::__alloc_traitsstd::allocator<Reservation::information, Reservation::information>::value_type' {aka 'Reservation::information'})| I'm a beginner using vector, please help me. I'm trying to create a reservation that ask information of the user, however I getting an error.I dont know what to do. Any ideas?
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void details();
class Reservation{
private:
struct information
{
string name;
string mobileNum;
};
vector<information> list_of_reservation;
public:
void details()
{
string back;
information l;
cout << "WELCOME TO AIRLINES\n";
for (int i = 0; i < 100; i++){
cout << "What is your name: ";
cin >> ws;
getline (cin, l.name);
cout << "What is your number: ";
cin >> l.mobileNum;
back:
cout << "Do you want another reservation? Y/N:";
cin >> back;
if (back == "Y" || back == "y")
{
cout << endl
<< endl;
cout << "You filled all Entries of traveler successfully...\n";
}
else if (back == "N" || back == "n")
{
cout << endl
<< endl;
cout << "You filled all Entries of traveler successfully...\n";
break;
}
else
{
cout << "Wrong Input";
goto back;
}
list_of_reservation.push_back(l);
}
cout << "You entered: " << list_of_reservation.size() << endl;
for (int i = 0; i < list_of_reservation.size(); i++)
{
cout << "the names are: " << list_of_reservation[i] << endl;
}
/*for (int i = 0; i < m.list_of_mobileNum.size(); i++)
{
cout << "the numbers are: " << m.list_of_mobileNum[i] << endl;
}*/
}
};
int main(){
cout << "Welcome to airlines details please confirm\n";
Reservation obj;
obj.details();
return 0;
}
Might be a stupid question, but I can't find anywhere something to help. I'm trying to draw in OpenGL 2 vectors with a given angle (in radians) between them, something like this:
I managed to draw the vectors but I'm not sure how to place them at the specific angle:
glBegin(GL_LINES); // Vx
glColor4f(1, .5, 0, 1);
glVertex3f(0, 0, 0);
glVertex3f(0, vectorYRScalingValue, 0); // vectorYRScalingValue is 5.0
glEnd();
glBegin(GL_LINES); // Vy
glColor4f(1, .5, 0, 1);
glVertex3f(0, 0, 0);
glVertex3f(0, vectorYRScalingValue, 0);
glEnd();
I want to determine the type of this
variable inside a class method.
For example, take the following example -
#include <iostream>
#include <cstdlib>
#include <map>
class Base{
};
using getPrintString = std::map<Base, std::string>;
class A : public Base{
public:
void print(getPrintString& stringMap){
std::string toPrint = stringMap[std::remove_reference<decltype(*this)>::type];
std::cout<<toPrint<<std::endl;
}
};
class B: public Base{
public:
void print(getPrintString& stringMap){
std::string toPrint = stringMap.at(std::remove_reference<decltype(*this)>::type);
std::cout<<toPrint<<std::endl;
}
};
getPrintString stringMap{
{std::declval<A>(), "A String"},
{std::declval<B>(), "B String"}
};
int main()
{
A a;
B b;
a.print(stringMap);
b.print(stringMap);
}
In the above code, I want to decide what to print, depending on which class is calling the print
method. I thought the class type of the method can be ascertained using decltype(*this)
. as for any Class type X
, this
will be a pointer of type X*
, followed by std::remove_reference
, as I am using decltype
on a variable.
However, upon compilation, I run into the following error -
test.cpp: In member function ‘void A::print(getPrintString&)’:
test.cpp:15:85: error: expected primary-expression before ‘]’ token
15 | std::string toPrint = stringMap[std::remove_reference<decltype(*this)>::type];
| ^
test.cpp: In member function ‘void B::print(getPrintString&)’:
test.cpp:23:88: error: expected primary-expression before ‘)’ token
23 | std::string toPrint = stringMap.at(std::remove_reference<decltype(*this)>::type);
| ^
In file included from /usr/include/c++/11/bits/move.h:57,
from /usr/include/c++/11/bits/exception_ptr.h:43,
from /usr/include/c++/11/exception:153,
from /usr/include/c++/11/ios:39,
from /usr/include/c++/11/ostream:38,
from /usr/include/c++/11/iostream:39,
from test.cpp:1:
/usr/include/c++/11/type_traits: In instantiation of ‘decltype (__declval<_Tp>(0)) std::declval() [with _Tp = A; decltype (__declval<_Tp>(0)) = A&&]’:
test.cpp:29:21: required from here
/usr/include/c++/11/type_traits:2366:47: error: static assertion failed: declval() must not be used!
2366 | static_assert(__declval_protector<_Tp>::__stop,
| ^~~~~~
/usr/include/c++/11/type_traits:2366:47: note: ‘std::__declval_protector<A>::__stop’ evaluates to false
/usr/include/c++/11/type_traits: In instantiation of ‘decltype (__declval<_Tp>(0)) std::declval() [with _Tp = B; decltype (__declval<_Tp>(0)) = B&&]’:
test.cpp:30:21: required from here
/usr/include/c++/11/type_traits:2366:47: error: static assertion failed: declval() must not be used!
/usr/include/c++/11/type_traits:2366:47: note: ‘std::__declval_protector<B>::__stop’ evaluates to false
In file included from /usr/include/c++/11/string:48,
from /usr/include/c++/11/bits/locale_classes.h:40,
from /usr/include/c++/11/bits/ios_base.h:41,
from /usr/include/c++/11/ios:42,
from /usr/include/c++/11/ostream:38,
from /usr/include/c++/11/iostream:39,
from test.cpp:1:
/usr/include/c++/11/bits/stl_function.h: In instantiation of ‘constexpr bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = Base]’:
/usr/include/c++/11/bits/stl_tree.h:2174:33: required from ‘std::pair<std::_Rb_tree_node_base*, std::_Rb_tree_node_base*> std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_get_insert_hint_unique_pos(std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::const_iterator, const key_type&) [with _Key = Base; _Val = std::pair<const Base, std::__cxx11::basic_string<char> >; _KeyOfValue = std::_Select1st<std::pair<const Base, std::__cxx11::basic_string<char> > >; _Compare = std::less<Base>; _Alloc = std::allocator<std::pair<const Base, std::__cxx11::basic_string<char> > >; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::const_iterator = std::_Rb_tree<Base, std::pair<const Base, std::__cxx11::basic_string<char> >, std::_Select1st<std::pair<const Base, std::__cxx11::basic_string<char> > >, std::less<Base>, std::allocator<std::pair<const Base, std::__cxx11::basic_string<char> > > >::const_iterator; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::key_type = Base]’
/usr/include/c++/11/bits/stl_tree.h:2234:4: required from ‘std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_unique_(std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::const_iterator, _Arg&&, _NodeGen&) [with _Arg = const std::pair<const Base, std::__cxx11::basic_string<char> >&; _NodeGen = std::_Rb_tree<Base, std::pair<const Base, std::__cxx11::basic_string<char> >, std::_Select1st<std::pair<const Base, std::__cxx11::basic_string<char> > >, std::less<Base>, std::allocator<std::pair<const Base, std::__cxx11::basic_string<char> > > >::_Alloc_node; _Key = Base; _Val = std::pair<const Base, std::__cxx11::basic_string<char> >; _KeyOfValue = std::_Select1st<std::pair<const Base, std::__cxx11::basic_string<char> > >; _Compare = std::less<Base>; _Alloc = std::allocator<std::pair<const Base, std::__cxx11::basic_string<char> > >; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator = std::_Rb_tree<Base, std::pair<const Base, std::__cxx11::basic_string<char> >, std::_Select1st<std::pair<const Base, std::__cxx11::basic_string<char> > >, std::less<Base>, std::allocator<std::pair<const Base, std::__cxx11::basic_string<char> > > >::iterator; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::const_iterator = std::_Rb_tree<Base, std::pair<const Base, std::__cxx11::basic_string<char> >, std::_Select1st<std::pair<const Base, std::__cxx11::basic_string<char> > >, std::less<Base>, std::allocator<std::pair<const Base, std::__cxx11::basic_string<char> > > >::const_iterator]’
/usr/include/c++/11/bits/stl_tree.h:1102:23: required from ‘std::__enable_if_t<std::is_same<_Val, typename std::iterator_traits<_InputIterator>::value_type>::value> std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_range_unique(_InputIterator, _InputIterator) [with _InputIterator = const std::pair<const Base, std::__cxx11::basic_string<char> >*; _Key = Base; _Val = std::pair<const Base, std::__cxx11::basic_string<char> >; _KeyOfValue = std::_Select1st<std::pair<const Base, std::__cxx11::basic_string<char> > >; _Compare = std::less<Base>; _Alloc = std::allocator<std::pair<const Base, std::__cxx11::basic_string<char> > >; std::__enable_if_t<std::is_same<_Val, typename std::iterator_traits<_InputIterator>::value_type>::value> = void; typename std::iterator_traits<_InputIterator>::value_type = std::pair<const Base, std::__cxx11::basic_string<char> >]’
/usr/include/c++/11/bits/stl_map.h:232:36: required from ‘std::map<_Key, _Tp, _Compare, _Alloc>::map(std::initializer_list<std::pair<const _Key, _Tp> >, const _Compare&, const allocator_type&) [with _Key = Base; _Tp = std::__cxx11::basic_string<char>; _Compare = std::less<Base>; _Alloc = std::allocator<std::pair<const Base, std::__cxx11::basic_string<char> > >; std::map<_Key, _Tp, _Compare, _Alloc>::allocator_type = std::allocator<std::pair<const Base, std::__cxx11::basic_string<char> > >]’
test.cpp:31:1: required from here
/usr/include/c++/11/bits/stl_function.h:400:20: error: no match for ‘operator<’ (operand types are ‘const Base’ and ‘const Base’)
400 | { return __x < __y; }
Filtering out, there are two main error - first
test.cpp: In member function ‘void A::print(getPrintString&)’:
test.cpp:15:85: error: expected primary-expression before ‘]’ token
15 | std::string toPrint = stringMap[std::remove_reference<decltype(*this)>::type];
| ^
test.cpp: In member function ‘void B::print(getPrintString&)’:
test.cpp:23:88: error: expected primary-expression before ‘)’ token
23 | std::string toPrint = stringMap.at(std::remove_reference<decltype(*this)>::type);
|
Which comes from the use of decltype
. How to use decltype
correctly in this context. Second, there is an another internal error using declval
, what am I doing wrong and how to fix it ?
TIA
everyone . I'm trying to use abs(), but my ide says:
"abs" is ambiguous
Here's my code :
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double x = -87.91, result;
result = abs(x);
cout<<result;
return 0;
}
What should I do to fix that?
I tried to to use fabs(), but that's not what I need.
In the model-checked implementation of the CL-Deque, they use the following strategy to decrement the bottom
pointer:
size_t b = atomic_load_explicit(&q->bottom, memory_order_relaxed) - 1;
Array *a = (Array *) atomic_load_explicit(&q->array, memory_order_relaxed);
atomic_store_explicit(&q->bottom, b, memory_order_relaxed);
atomic_thread_fence(memory_order_seq_cst);
So they load the bottom
pointer, decrement it locally, then store it. Why is it valid to do this? Wouldn't a concurrent thief be able to see either one of the bottom
values?
An alternative way to perform this would be to combine the read-modify-write operation into a single atomic_fetch_sub
, like so:
Array *a = (Array *) atomic_load_explicit(&q->array, memory_order_relaxed);
size_t b = atomic_fetch_sub_explicit(&q->bottom, 1, memory_order_seq_cst) - 1;
This would remove that possible race condition.
I think that the broken-up version is valid because of the CAS inside of the steal
and take
functions resolves this race later, only if the deque is small enough for it to matter. But is this a general technique?
I am new to templates and lambdas function and I am trying to understand what's happening in this piece of code:
function<void (const int &)> foo = [&](auto x) {
x = 42;
}
Here, I assume the compiler is able to tell from the auto
keyword that x
has type const int &
. Therefore, the compiler should not allow the assignment x = 42
.
However, this code compiles without error, which confuses me. Why does the compiler allow this? What did the compiler actually deduced for the auto
keyword?
Regarding
vector<double> v2 = 9; //error: no conversion from int to vector
, is there no conversion from
int
to
vector<double>
because
std::vector<double>(int)
is explicit?
Would it have been possible to have had a type conversion of type floating-integral conversion in the case of it not having been declared explicit?
I am new to move semantics and want to understand what's happening in this piece of code:
vector<int> create_vector() {
return {0, 1, 2};
}
for (int &x : create_vector()) {
/* ... */
}
If I understand correctly, the function call create_vector()
returns an rvalue. Therefore, the elements inside it should be rvalues as well (i.e. 0, 1, 2 are rvalues). However, in the range for loop, we are binding these rvalues to a non-const lvalue reference int &x
, which shouldn't be allowed? I thought non-const lvalue references can only bind to lvalues, not rvalues.
What's happening here? Why is this allowed?
Suppose I need to write a function which might take either a constant reference to an lvalue or a temporary value, is there any advantage in terms of performance in writing both overloads, the one taking a const T& and one taking T&&, if we do not want to move from the rvalue?
I was assuming having two overloads (or just writing the function once with universal references) would be beneficial but I can't pin down the exact reason. I even tried a small example: https://godbolt.org/z/53r34x4Mj but I can't really make sense of the generated code.
gsl::not_null has 2 constructors one taking a forwarding reference and another one taking a value type. What is the case where the forwarding constructor alone would not work? Implementation from here
template <class T>
class not_null
{
public:
static_assert(details::is_comparable_to_nullptr<T>::value, "T cannot be compared to nullptr.");
template <typename U, typename = std::enable_if_t<std::is_convertible<U, T>::value>>
constexpr not_null(U&& u) : ptr_(std::forward<U>(u))
{
Expects(ptr_ != nullptr);
}
template <typename = std::enable_if_t<!std::is_same<std::nullptr_t, T>::value>>
constexpr not_null(T u) : ptr_(std::move(u))
{
Expects(ptr_ != nullptr);
}
...
I'm not allowed to make any definition in the header file, only declarations. So I have the following .h file:
class read_error final: public std::runtime_error {
public:
enum class Code: uint8_t;
read_error(Code code);
Code getCode() const throw();
private:
Code code;
static std::string whatFromCode(Code code);
};
And in the .cpp file I want to do this:
enum class read_error::Code: uint8_t {
TIME_OUT,
DESERIALIZE,
CHECKSUM,
START_BYTE,
END_BYTE,
COMMAND
};
And I mean, that part does compile, but when I try to throw this error like read_error(read_error::Code::CHECKSUM);
I get the the following: error: ‘CHECKSUM’ is not a member of ‘amp::exception::read_error::Code’
I put both the cpp and the h into my makefile but it doesn't seem to find the definition. Is there any other way than defining the enum class in the .h file?
I'm trying to write an error that derives from runtime_error.
Here's the definition:
class read_error final: public std::runtime_error {
public:
enum class Code;
read_error(Code code);
const char* what() const throw();
Code getCode() const throw();
private:
Code code;
};
And I'm trying to call the constructor like so:
read_error::read_error(Code code): code(code) {
std::string _what;
switch (code) {
case Code::TIME_OUT:
_what = "Read exception: Reading timed out";
case Code::DESERIALIZE:
_what = "Read exception: Something went wrong while deserializing the object";
case Code::CHECKSUM:
_what = "Read exception: Mismatched checksum";
case Code::NO_START_BYTE:
_what = "Read exception: Malformed message, no start byte at front";
case Code::NO_END_BYTE:
_what = "Read exception: Malformed message, no end byte at back";
runtime_error(_what);
}
}
But that doesn't work. It seems that I have to use the initializer like
read_error::read_error(Code code): code(code), runtime_error(/*something*/) {}
But I can't put a switch statement in there. How do I work around this? I know that I have to initialize it, but I can't edit the what_arg inside the runtime_error after the initialization. How do I initialize it using that switch statement?
(I know that there's something still wrong with the enum class definition, I'm working on that too)
enter image description here Can someone please explain me what is wrong here? The code runs but still there's some problem.
Hopefully someone can has the answer to my problem.
I have a template class that stores vectors in a vector:
template <class T, typename T::value_type SepC, typename T::value_type HigC, typename CharT = typename T::value_type>
class book {
private:
std::vector< std::vector<T> > content_;
The T can be any container type (for example string, or list).
I have tried to iterate through the content_ with iterators, but not really working for me.
Could someone show me the right way to do it? What can be the problem?
The following construct in main()
retrieves a class member's offset
at runtime:
struct Base
{
virtual ~Base() = default;
};
struct Cls : public virtual Base
{
int a, b;
};
int main()
{
int Cls::* ptr = &Cls::a;
unsigned long offset = *reinterpret_cast<unsigned long*>(&ptr);
}
The class layout is determined at compile time and doesn't change. So, it would be beneficial to make this a constexpr
.
Unfortunately, the above assignment requires an lvalue.
How can I get the same result using a constexpr
?
string longestCommonPrefix(vector<string>& strs) {
if (strs.empty())
{
return "";
}
for (int i = 1; i < strs.size(); ++i)
{
while (strs[i].find(strs[0]) != 0)
{
strs[0].pop_back();
if (strs[0] == "")
{
return "";
}
}
}
return strs[0];
}
I want to analyze the efficiency of the algorithm. I think that the auxiliary space complexity is O(1) but I couldn't figure out time complexity of the function. What is its time complexity?
Thanks.
I got some data coming in over an RS485 line. I store that data in a vector<char>
and now I need to cast that to several types. Currently that is done by the following function:
template<typename To>
static std::size_t parseBinaryToType(const char* input, To& destination) {
destination = *(reinterpret_cast<const To*>(input)); //FIXME
return sizeof(destination);
}
//EXAMPLE
enum class SomeEnum: uint16_t {
BAR,
BAZ
}
class Foo {
SomeEnum m_Enum;
uint8_t m_Int;
bool m_Bool;
public:
static Foo deserializeFrom(const char* const buffer) {
Foo result;
offset = 0;
offset+= parseBinaryToType(buffer + offset, result.m_Enum);
offset+= parseBinaryToType(buffer + offset, result.m_Int);
offset+= parseBinaryToType(buffer + offset, result.m_Bool);
return result;
}
}
But I find this very unsafe. Especially due to the reinterpret_cast
and the fact that it doesn't check for endianness.. Is there a safe way to do this in cpp?
Edit: I have readed What are the rules about using an underscore in a C++ identifier?
that post does not answer what is explicitly allowed in [reserved.names](17.6.4.3)/2 and why a name that begins with an underscore followed by an lowercase letter in local namespace is explicitly allowed. In fact, I don't really think that is explicitly allowed and might be UB if we do that.
the following is the original question:
first at all, let's see the standard(ISO/IEC 14882:2011(E))
[reserved.names](17.6.4.3) said:
1 The C++ standard library reserves the following kinds of names:
— macros
— global names
— names with external linkage2 If a program declares or defines a name in a context where it is reserved, other than as explicitly allowed by this Clause, its behavior is undefined.
[global.names](17.6.4.3.2) said:
1 Certain sets of names and function signatures are always reserved to the implementation:
— Each name that contains a double underscore __ or begins with an underscore followed by an uppercase letter (2.12) is reserved to the implementation for any use.
— Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.
for now, if we have the following code:
int _a1;
int _A1;
void f()
{
int _a2 = 0;
int _A2 = 0;
}
Q1: Is the behavor is undefined if we defines _a1?
Q2: Is the behavor is undefined if we defines _A1?
Q3: Is the behavor is undefined if we defines _a2?
Q4: Is the behavor is undefined if we defines _A2?
In the standard [global.names](17.6.4.3.2) tells us Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.
Q5: Does that means we can use a name that begins with an underscore followed by an lowercase letter in local namespace? If so is that so-called explicitly allowed?
In fact I have read a answer that tells me that I can use a name that begins with an underscore followed by an lowercase letter, but I'm not sure if that is explicitly allowed so I have no idea about whether that answer is correct.
I have a question on window folder property. When I'm checking property it's shows two size that is size and disk on size. So whenever I'm using qfileinfo it's show only size of folder. But i need "Size on disk". So what's is the method to get size on disk. And please explain that why is happening.
Help me for this.
Thanks in advance.
I want to check size on disk by qt C++ language
my simple test code here:
// t.cpp
#include <iostream>
#include <chrono>
#include <thread>
void fcn()
{
uint8_t i = 0;
while (true)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
std::cout<<"hihi" << float(i++)<<std::endl;
}
}
std::thread t(fcn);
t.detach(); // detach position A
int main()
{
// t.detach(); // detach position B
uint8_t i = 0;
while (true)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
std::cout<<"yoyo" << float(i++)<<std::endl;
}
}
compile and run by g++ ./t.cpp -o t -lpthread; ./t
;
when detach at position A
got compile error error: ‘t’ does not name a type | t.detach();
, but detach at position B
is ok.
why is this different?
my situation is that i wish to move the fcn()
and std::thread t(fcn)
as well as t.detach()
into a standalone header file later (for a better orginazation of the project) thanks
I'm working on a cryptocurrency app (for uni) and I have a class called orderBook which reads data off CSV file and does some processing. One of the class' functions is getKnownProducts, which prints all currencies as strings.
OrderBookEntry is the main class with the constructor that contains all the datatypes of the data read from the CSV.
I want to call the function getKnownProducts in a function that lists all products.
class OrderBook
{
public:
/** Construct, reading a csv file*/
OrderBook(std::string filename);
/** Return vector of all known products in the dataset*/
std::vector<std::string> getKnownProducts();
//some more code...
};
I made an instance in the main file
OrderBook OrderBook{"20200601.csv"};
And this is the implementation in the cpp file
std::vector<std::string> OrderBook::getKnownProducts()
{
std::vector<std::string> products;
std::map< std::string, bool> prodMap;
for(OrderBookEntry& e : orders)
{
prodMap[e.product] = true;
}
// Flatten map to a vector of strings
for(const auto& productStringBoolPair : prodMap)
{
products.push_back(productStringBoolPair.first);
}
return products;
}
Finally, I tried to call getKnownProducts from the following function when I got the typename error
void printProducts()
{
for(std::string const& p : OrderBook.getKnownProducts())
{
std::cout << "products: " << p << std::endl;
}
}
How to get the result of EXPECT_EXIT() in gtest?
I want to do something according to the results of EXPECT_EXIT. For example:
for(int i = 0; i < 1000; i++) {
for(int j = 0; j < 10; j++) {
auto &result = EXPECT_EXIT(Function(i, inputs[j]));
if (result) {
do something;
break; //jump out of the loop
}
}
}
I'm getting a warning while running static code analysis, as below: This output parameter value is not subsequently checked.
And in the code I was using a variable which is non Bool. Can someone help me here?
Here is the code in c++.
class A {
private:
A() {};
void xx_func() {}
void yy_func() {}
public:
~A() {};
static A &GetInstance() {
static A a_ins;
return a_ins;
}
static void func1() {
A::GetInstance().xx_func();
// other code
}
static void func2() {
A::GetInstance().yy_func();
//other code
}
};
The GetInstance
function return a local static variable. Is it safe for func1
、 func2
to call A::GetInstance()
?
i am comparing 3 number and the output must show which one is largest and which one is smallest but the thing is what if there are unlimited number I will have to write a lot of ifs and else, so for that purpose can you pls convert this into for loop for me.
int main()
{
float number1;
float number2;
float number3;
cout << "Please enter Number 01:";
cin >> number1;
cout << "Please enter Number 02:";
cin >> number2;
cout << "Please enter Number 03:";
cin >> number3;
if (number1 > number2 && number1 > number3) {
cout <<”Number 01 is maximum…”<< endl;
}
else if (number2 > number1 && number2 > number3) {
cout << "Number 02 is maximum…" << endl;
}
else if (number3 > number1 && number3 > number2) {
cout << "Number 03 is maximum…" << endl;
}
Else
{
Cout <<”Invalid entry from maximum”<< endl;
}
If(number1 < number2 && number1 < number3)
{
Cout <<”Number 01 is minimum..”<< endl;
}
else if (number2 < number1 && number2 < number3)
{
cout << "Number 02 is minimum…" << endl;
}
else if (number3 < number1 && number3 < number2)
{
cout << "Number 03 is minimum…" << endl;
}
Else
{
Cout<<”invalid entry for minimum”<<endl;
}
Return 0;
I'm trying to make universal function for generating a dynamic array with random elements and I want to use template, so I can choose data type whenever I want. The problem is:
LNK2019 unresolved external symbol "public: static double * __cdecl ArrayOperations<double>::GenerateRandomArray(double,double,unsigned int)" (?GenerateRandomArray@?$ArrayOperations@N@@SAPANNNI@Z) referenced in function _main Algorithms G:\PrivateRepositories\CppDirectory\Algorithms\Source.obj
my header file:
#include<random>
#include <iostream>
template<class T>
class ArrayOperations
{
public:
static T* GenerateRandomArray(T, T, size_t);
//static double* GenerateRandomArray(double, double, size_t);
};
and my source file:
#include "ArrayOperations.h"
template<class T>
T* ArrayOperations<T>::GenerateRandomArray(T a, T b, size_t size){
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_real_distribution<double> dist(a, b + 1.);
auto arr = std::make_unique<T>[size];
for (size_t i = 0; i < size; i++) {
arr[i] = dist(mt);
}
return arr;
}
main function:
int main() {
const size_t arrSize = 1000;
auto arr = ArrayOperations<double>::GenerateRandomArray(20.1, 50.5, arrSize);
for (size_t i = 0; i < arrSize; i++){
std::cout << arr[i] << ",";
}
}
I can't find the solution on the internet. Code works well when i remove templates and replace them with eg. int or double.
I am trying to implement a simple Abstract Factory Design Pattern using unique pointers in C++. I am following this link as reference (but modified a bit). The link uses raw pointers and I want to use unique ptrs instead. Please find the code below. Problem: Segmentation fault. I can't point my finger where this fault is arising from.
devices.hpp:
#ifndef PHONE_HPP
#define PHONE_HPP
#include <iostream>
#include <string>
class phone
{
public:
virtual std::string get_name() const = 0;
};
class iphone : public phone
{
public:
std::string get_name() const override;
};
class android : public phone
{
public:
std::string get_name() const override;
};
class laptop
{
public:
virtual std::string get_name() const = 0;
};
class mac : public laptop
{
public:
std::string get_name() const override;
};
class chromebook : public laptop
{
public:
std::string get_name() const override;
};
devices.cpp
#include <iostream>
#include <string>
#include "phone.hpp"
std::string iphone::get_name() const {
return "iPhone X";
}
std::string android::get_name() const {
return "Pixel 6";
}
std::string mac::get_name() const {
return "Macbook Air";
}
std::string chromebook::get_name() const {
return "Chrome Flex";
}
device_manufacturer.hpp file:
#ifndef DEVICE_MANUFACTURER_HPP
#define DEVICE_MANUFACTURER_HPP
#include <iostream>
#include <string>
#include <memory>
#include "phone.hpp"
class device_manufacturer
{
public:
enum Manufacturer{APPLE, GOOGLE};
virtual std::unique_ptr<phone> get_phone() const = 0;
virtual std::unique_ptr<laptop> get_laptop() const = 0;
static std::unique_ptr<device_manufacturer> create_device(const Manufacturer& manf_input);
};
class Apple : public device_manufacturer
{
public:
std::unique_ptr<phone> get_phone() const override;
std::unique_ptr<laptop> get_laptop() const override;
};
class Google : public device_manufacturer
{
public:
std::unique_ptr<phone> get_phone() const override;
std::unique_ptr<laptop> get_laptop() const override;
};
device_manufacturer.cpp:
#include <iostream>
#include <string>
#include <memory>
#include "device_manufacturer.hpp"
#include "phone.hpp"
std::unique_ptr<device_manufacturer> device_manufacturer::create_device(const Manufacturer& manf_input){
std::unique_ptr<device_manufacturer> manf_ptr;
if (manf_input == Manufacturer::APPLE)
{
manf_ptr = std::make_unique<Apple>();
}
if (manf_input == Manufacturer::GOOGLE)
{
manf_ptr = std::make_unique<Google>();
}
return manf_ptr;
}
std::unique_ptr<phone> Apple::get_phone() const {
return std::unique_ptr<iphone>();
}
std::unique_ptr<phone> Google::get_phone() const {
return std::unique_ptr<android>();
}
std::unique_ptr<laptop> Apple::get_laptop() const {
return std::unique_ptr<mac>();
}
std::unique_ptr<laptop> Google::get_laptop() const {
return std::unique_ptr<chromebook>();
}
And finally the client code:
main.cpp:
#include <iostream>
#include <string>
#include <memory>
#include "device_manufacturer.hpp"
#include "phone.hpp"
int main(){
std::unique_ptr<device_manufacturer> manf = device_manufacturer::create_device(device_manufacturer::Manufacturer::APPLE);
std::cout << manf->get_laptop()->get_name() << std::endl;
return 0;
}
I wrote this code,and i was trying to get an error from freeing the memory twice because of the shallow copying of objectsenter image description here
but i found out that the compiler did not complain and it compiles successfully without any errors, does anyone knows why, I watched youtube videos and they were getting error from the same code. did i write something wrong or the memory is not really freed?
I wrote some
template<typename ...T>
inline ARRAY<typename std::common_type<T...>::type, sizeof...(T)> make_array_(const T&..._r)
{ return ARRAY<typename std::common_type<T...>::type, sizeof...(T)>(_r...);
}
which creates a symbol
0000000000000361 t namespace::ARRAY_IMPL<std::common_type<double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double>::type, sizeof (double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double), std::is_trivial<std::common_type<double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double>::type>::value> namespace::make_array_<double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double>(double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&, double const&)
Why is std::common_type<double, double, double>::type not collapsing? g++ version is 5.3.0.
#include <type_traits>
template<typename T, std::size_t SIZE>
struct ARRAY
{ template<typename ...T1>
ARRAY(T1&&...)
{
}
};
template<typename ...T>
inline ARRAY<typename std::common_type<T...>::type, sizeof...(T)> make_array_(const T&..._r)
{ return ARRAY<typename std::common_type<T...>::type, sizeof...(T)>(_r...);
}
const auto sA = make_array_(1.0, 2.0, 3.0);
int main(int, char**)
{
}
#include <iostream>
#include <list>
using namespace std;
int main() {
list<int> A;
A.push_back(1);
A.push_back(2);
A.push_back(3);
auto it = A.begin();
cout << *it << ' ';
advance(it, 1);
cout << *it << ' ';
advance(it, 1);
cout << *it << ' ';
advance(it, 1);
cout << *it << ' ';
advance(it, 1);
cout << *it << ' ';
}
I belive that list
is a double linked list. Surprisingly, the output is 1 2 3 3 1
. Can someone explain what's happening here? Here are questions:
3
. Here, an additional advance
moves the iterator to A.end()
. I believe that A.end()
is an imaginary node that does not point to the original element. However, it prints out 3
. Why?1
at the end? The list
is not a circular queue.Why does a static constexpr array work and a static constexpr std::array not? C++11
struct FixedParameters{
using LookUpTable = std::array<std::pair<float, float>, 1>;
static constexpr LookUpTable lookUpTable};
static constexpr std::pair<float, float> array[]=0.1;
static constexpr int value = 42;
};
int main(){
std::cout << FixedParameters::lookUpTable[0].second << std::endl; //error
std::cout << FixedParameters::array[0].second << std::endl; // ok
std::cout << FixedParameters::value << std::endl; // ok
}
// PS D:\...\Constexpr> clang++ *.cpp
// lld-link: error: undefined symbol: FixedParameters::lookUpTable
// >>> referenced by C:\../constexpr-d4252b.o:(.refptr._ZN15FixedParameters11lookUpTableE)
// clang++: error: linker command failed with exit code 1 (use -v to see invocation)
I want to write a formatToStr()
which receives a format in const char*
and returns the formatted string.
My formatToStr()
sometimes may not receive parameters, as printf()
function.
#include <string>
template<typename... Args>
static inline std::string formatToStr(const char* format, const Args&... args) {
char buff[1024];
snprintf(buff, sizeof(buff), format, args...);
return std::string(buff);
}
int main() {
printf("%s\n", FormatToStr("test").c_str());
return 0;
}
This code provides a warning:
$ g++ --version
g++ (Ubuntu 11.3.0-1ubuntu1~22.04) 11.3.0
...
$ g++ ./z.cpp
./z.cpp: In instantiation of ‘std::string formatToStr(const char*, const Args& ...) [with Args = {}; std::string = std::__cxx11::basic_string<char>]’:
./z.cpp:11:28: required from here
./z.cpp:6:17: warning: format not a string literal and no format arguments [-Wformat-security]
6 | snprintf(buff, sizeof(buff), format, args...);
| ~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Is there a way to write better code to remove this warning? I can always ignore
it, but I wish to solve it in a better way.
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat-security"
...
#pragma GCC diagnostic pop
Thanks
hmmm.Sorry but I think my question is very specific that I want to know how should I generate c++ code from json data..
I am getting a json response from one request ( the response ie the json will always contain accounts
array with 0 to 25 elements)
for eg consider below response : res
res = {
"accounts": [
{
"name": "CandyMachine",
"type": {
"kind": "struct",
"fields": [
{
"name": "authority",
"type": "string"
},
{
"name": "wallet",
"type": "string"
},
{
"name": "tokenMint",
"type": "string"
},
{
"name": "itemsRedeemed",
"type": "u64"
},
{
"name": "data",
"type": "string"
}
]
}
},
{
"name": "CollectionPDA",
"type": {
"kind": "struct",
"fields": [
{
"name": "mint",
"type": "string"
},
{
"name": "candyMachineNo",
"type": "u64"
}
]
}
},
{
"name": "FreezePDA",
"type": {
"kind": "struct",
"fields": [
{
"name": "candyMachine",
"type": "string"
},
{
"name": "allowThaw",
"type": "bool"
},
{
"name": "frozenCount",
"type": "u64"
},
{
"name": "mintStart",
"type": "string"
},
{
"name": "freezeTime",
"type": "u64"
},
{
"name": "freezeFee",
"type": "u64"
}
]
}
}
]
}
Now according to above json response. I want to create class for each of the element of accounts array automatically
To do the above, I found this ts library through which I can generate typescript class by doing this way.
import { Project } from "ts-morph"
const project = new Project()
idl.accounts?.forEach((acc) => {
const src = project.createSourceFile(
outPath(`accounts/${acc.name}.ts`),
"",
{
overwrite: true,
}
)
const fields = acc.type.fields
const name = acc.name
const cls = src.addClass({
isExported: true,
name: name,
properties: fields.map((field) => {
return {
isReadonly: true,
name: field.name,
type: field.type
}
}),
})
}
which creates this typescript class
export class CandyMachine {
readonly authority: string
readonly wallet: string
readonly tokenMint: string
readonly itemsRedeemed: number
readonly data: string
}
export class CollectionPDA {
readonly mint : string
readonly candyMachineNo: number
}
But I want to create similar class but in C++.
ie
class CandyMachine
{
std::string authority,
std::string wallet,
std::string tokenMint,
uint64 itemsRedeemed,
std::string data,
}
class CollectionPDA
{
std::string mint,
uint64 candyMachineNo,
}
similarly for FreezePDA.
Can someone please tell me any way to achieve this ? How to generate C++ code ?