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
|
|---|---|---|---|---|
73,304,742
| 73,304,803
|
Does std::make_tuple() not work with objects of type std::optional?
|
This is the source code:
using namespace std;
class obj {
public:
obj() = default;
obj(int i) : i_{i} {}
int I() const {return i_;}
int const & rI() const {return i_;}
void I(int i) {i_ = i;}
void show() const {cout << "addr = " << this << ", i_ = " << I() << endl;}
private:
int i_{0};
};
struct {
optional<obj> o_0 {nullopt};
optional<obj> o_1 {nullopt};
optional<obj> o_2 {nullopt};
void set_o0(obj o_) {o_0 = o_;}
void set_o1(obj o_) {o_1 = o_;}
void set_o2(obj o_) {o_2 = o_;}
tuple<optional<obj>, optional<obj>, optional<obj>> get_obj() {
return make_tuple<o_0, o_1, o_2>;
}
} opts_;
Trying to return a std::tuple composed of type std::optional<> does not seem to work. The following error message is reported which is not particularly that helpful. Can anyone help?
<source>: In member function 'std::tuple<std::optional<obj>, std::optional<obj>, std::optional<obj> ><unnamed struct>::get_obj()':
<source>:40:27: error: use of 'this' in a constant expression
40 | return make_tuple<o_0, o_1, o_2>;
| ^~~
<source>:40:32: error: use of 'this' in a constant expression
40 | return make_tuple<o_0, o_1, o_2>;
| ^~~
<source>:40:37: error: use of 'this' in a constant expression
40 | return make_tuple<o_0, o_1, o_2>;
| ^~~
<source>:40:16: error: cannot resolve overloaded function 'make_tuple' based on conversion to type 'std::tuple<std::optional<obj>, std::optional<obj>, std::optional<obj> >'
40 | return make_tuple<o_0, o_1, o_2>;
| ^~~~~~~~~~~~~~~~~~~~~~~~~
|
std::make_optional is a function template. Its purpose is to deduce the tuples types from the parameters passed to it.
Rather than explicitly listing the template arguments you should let them be deduced from the parameter. And you need to actually call the function:
auto get_obj() {
return std::make_tuple(o_0, o_1, o_2);
}
Note that you can use auto for the return type. If you do not use the auto return type you do not need make_tuple (because as I said, its purpose is to deduce the tuples types, but when the type is already known this isnt required):
std::tuple<std::optional<obj>, std::optional<obj>, std::optional<obj>> get_obj() {
return {o_0, o_1, o_2};
}
|
73,305,510
| 73,306,143
|
Does using a pointer to access memory in a loop affect program efficiency?
|
Here is an illustration:
#include <stdio.h>
void loop(int *a)
{
int b = *a;
for (int i = 0; i < b; ++i)
{
;
}
}
void loop_pointer(int *a)
{
for (int i = 0; i < *a; ++i)
{
;
}
}
int main(void)
{
// Nothing to see here
return 0;
}
In the loop function, the memory is first stored on the stack and then accessed on every iteration. The memory would be cached.
My question is the following:
Could the indirection in the loop_pointer function result in cache misses? And if so, would a cache miss only occur when the memory is modified(written to) and then accessed(read from) or would it happen on every read?
|
Yes, referring to objects using pointers can impair efficiency. Consider this code:
void foo(int *a, int *b)
{
for (int i = 0; i < *a; ++i)
*b++ = SomeCalculation(i);
}
After *b++ = SomeCalculation(i);, has the value of *a changed? The compiler cannot know, because the caller might have passed an address for a that is somewhere in the memory that b++ will cover during the loop. Therefore, it must either reload *a after each iteration or it must generate extra code to compare a and b and the value of *a before the loop. (If that run-time test determines *b++ never updates the memory of a, it can branch to a loop like your first example, where *a is loaded once and cached. Otherwise, it must use branch to another loop that accounts for *a changing.)
C provides the restrict qualifier to tell the compiler that something like this will not happen. In this code:
void foo(int * restrict a, int *b)
{
…
}
the compiler may assume that *a never changes while foo is executing except through a. (restrict does allow this change to be indirect; if you have int *c = a; inside foo, then changing *a via *c is allowed with restrict, because the compiler can see c derives from a inside foo, but changing *a via b would violate the restrict.)
Similarly, one might wish to add restrict to the b parameter to tell the compiler that the things b points to are not affected by changes via other points.
|
73,305,611
| 73,305,827
|
How to exit a function with a return value without using "return" in c++
|
How would I exit a function with a return value without using return.
Is there something like this in c++ :
auto random_function() {
printf("Random string"); // Gets executed
exit_with_return_value(/* Any random value. */);
printf("Same string as before"); // Doesn't get executed
}
Because I'm aware about exit() which takes a exit code.
But is there any way I could exit with a return value.
It is just that I can't call return is parentheses like this:
( return /* random value*/ );
But I can call functions in parentheses,
(exit(0));
My use case:
template <typename ...Parameters>
class Parameter_Pack
{
private:
void* paramsAddr[sizeof...(Parameters)];
public:
Parameter_Pack(Parameters ...parameters) {
size_t count = 0;
((
parameters,
this->paramsAddr[count] = malloc(sizeof(Parameters)),
*(Parameters*)paramsAddr[count] = parameters,
count++
), ...);
}
auto operator[](size_t index) {
size_t count = 0;
try {
(((count == index ? : return *
(Parameters*)paramsAddr[index] : *
(Parameters*)paramsAddr[index]), count++), ...);
} catch (Parameters...) {
std::cout << "Error: " << std::endl;
}
}
const size_t size() const {
return sizeof...(Parameters);
}
};
The problem is I can't return in auto operator[](size_t index).
The compiler error is :
"expected primary-expression before 'return'"
|
return is a statement. Statements can't be part of a larger expression, so you can't return as a subexpression of some larger expression.
throw is an expression. It can be a subexpression of a larger expression, and you can throw any object you like.
It will be inconvenient for your callers, particularly if you mix it with an ordinary return. It will also not match the expectations other programmers have for how functions work. For that reason, I suggest you don't throw when you mean return.
|
73,305,616
| 73,305,663
|
why can't use ternary operator with different types when boost variable can hold multiple types?
|
I have something like below, but unable to compile it. I don't get it why I can't have different type when my variable can hold different types?
My code:
#include <boost/variant.hpp>
#include <iostream>
typedef boost::variant<int, float, double, std::string> MultiType;
int main() {
int a = 1;
std::string b = "b";
bool c = true;
MultiType d = c ? a : b;
return 0;
}
The error:
Error C2446 ':': no conversion from 'std::string' to 'int'
|
The expression c ? a : b has to have a type. There is no common type between std::string and int, so that expression is invalid.
There is a common type between std::string and MultiType, and between int and MultiType, so c ? MultiType{ a } : b is a valid expression, as is c ? a : MultiType{ b }
|
73,305,805
| 73,305,872
|
make -j and #pragma GCC diagnostic
|
Let's say I add the following to A.cpp
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
<code with unused parameters here>
#pragma GCC diagnostic pop
Then I build with "make -j." If "A.cpp" and "some_other_file_with_no_pragma.cpp" get built in parallel, will the #pragma above apply to both files? I would think not, but can't find a definitive answer.
|
Not unless you are doing some really weird stuff in your Makefile.
Compiler compiles each translation unit(.cpp+included .hpp) independently, meaning each pragma only applies to this one translation unit.
Running make -jN will execute N rules in parallel, each (line) in a separate shell process. Resulting in up to N parallel compilers which will not interfere with each other.
|
73,305,877
| 73,306,730
|
How to save the whole raw email on the file system?
|
I should save the entire structure of the emails that arrive at a mail server.
Using the "poco ++" libraries I was unable to save the email entirely in the file system. For the moment inside the class that inherits from MailMessage I am doing this:
MyMailMessage.h
class MyMailMessage: public MailMessage {
public:
bool WriteRawContent(int i);
};
MyMailMessage.cpp
bool MyMailMessage::WriteRawContent(int i)
{
std::cout << "Write Raw Content" << std::endl;
std::ofstream outfile("email.eml");
MessageHeader messageheader;
if(isMultipart()){
writeMultipart(messageheader, outfile);
}
else{
write(outfile);
}
std::cout << "Wrote it" << std::endl;
outfile.close();
return true;
}
With the write method I can only save a part:
Return-Path: <mail-test@cartellini.info>
Delivered-To: mail-test2@cartellini.info
Received: from server.mail (unknown [122.130.30.20]) by server.mail
Message-ID: <12314142test@webmail.it>
Date: Wed, 10 Aug 2022 12:41:28 +0200
Subject: test_subject
From: email-test@webmail.com
To: email-test2@webmail.com
User-Agent: Web-mail
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="----=_20220810124128_35847"
X-Priority: 3 (Normal)
Importance: Normal
------=_20220810124128_35847--
and with the writeMultiPart method:
Content-Type: multipart/mixed; boundary="----=_20220810124128_35847"
Mime-Version: 1.0
------=_20220810124128_35847--
I have to save the entire email with also the contents of the attachment or attachments in binary (and of the body if it is sent) like so :
Return-Path: <mail-test@webmail.com>
Delivered-To: mail-test2@webmail.com
Message-ID: <232131mail-test@webmail.com>
Date: Wed, 10 Aug 2022 12:41:28 +0200
Subject: test_subject
From: mail-test@webmail.com
To: mail-test2@webmail.com
User-Agent: WebMail
MIME-Version: 1.0
Content-Type: multipart/mixed;boundary="----=_20220211113523_23522"
X-Priority: 3 (Normal)
Importance: Normal
------=_20220211113523_23522
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 8bit
------=_20220211113523_23522
Content-Type: text/html; name="example.html"
Content-Transfer-Encoding: 8bit
Content-Disposition: attachment; filename="example.html"
<html>
<head><title>Email from webmail server</title></head>
<body>
<br>
Hi email test
</body>
</html>
------=_20220211113523_23522
Content-Type: application/xml; name="example.xml"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="example.xml"
PDS9DSAKQWEK123òSAD9213031ASDKSADSAKA9DSSDAU1293219KSADSAKSDA9213
PD93MNbnasdoaKSDAOWEQLDOWQELDWQDOSAD.SAD
so that it is possible to pass the file to the email decryption function and read it later as if it were going to read it directly from the email server.
EDIT
as suggested by @GusEvan i implemented latest function
void retrieveMessage(
int id,
std::ostream & ostr
);
To backup the email in raw format and then process it.
Here is the working version of the snippet:
POP3ClientSession ppcs(MAIL_SERVER);
std::ofstream outfile("email.eml");
std::ifstream infile("email.eml");
for (unsigned int i = 1; i <= messageInfoVec.size(); i++) {
ppcs.retrieveMessage(i,outfile);
mailMessage.read(infile,partHandler);
ProcessEmail(mailMessage,partHandler);
outfile.close();
infile.close();
}
|
The last retrieveMessage() overloaded method should be for you.
void retrieveMessage(
int id,
MailMessage & message,
PartHandler & handler
);
Retrieves the raw message with the given id from the server and copies it to the given output stream.
Check the documentation:
https://docs.pocoproject.org/current/Poco.Net.POP3ClientSession.html#27007
|
73,306,251
| 73,307,340
|
Can't compile code with libevent library using CMake
|
I use CMake in VS Code to build project with libevent. I add it to project
find_package(LIBEVENT REQUIRED)
target_link_libraries(${PROJECT_NAME}
PUBLIC
${LIBEVENT_LIB}
)
target_include_directories(${PROJECT_NAME}
PUBLIC
${LIBEVENT_INCLUDE_DIR}
)
And pass -levent flag to linker
target_link_options(TEST-CMAKE PUBLIC "-L/E:/Projects/C++/.libraries/libevent-2.1.12-stable/build/lib -levent -levent_core")
if i don't use any functions in code it compiles without errors, but if i use some, it fails with error
undefined reference to `event_base_dispatch' (same with other functions)
I found that problem might be in flag order, but i don't know how to change it in cmake
code i try to compile
#include <iostream>
#include <event2/event.h>
int main()
{
event_base* evbase;
event_base_dispatch(evbase);
}
I have Windows 10, GCC 11.3.0
CMakeLists.txt
cmake_minimum_required(VERSION 3.0.2)
project(TEST-CMAKE VERSION 0.1.0)
include(CTest)
enable_testing()
add_executable(TEST-CMAKE main.cpp)
find_package(LIBEVENT REQUIRED)
target_include_directories(${PROJECT_NAME}
PUBLIC
${LIBEVENT_INCLUDE_DIR}
)
target_link_libraries(${PROJECT_NAME}
PUBLIC
${LIBEVENT_LIB}
)
target_link_options(TEST-CMAKE PUBLIC "-L/E:/Projects/C++/.libraries/libevent-2.1.12-stable/build -levent -levent_core")
set(CPACK_PROJECT_NAME ${PROJECT_NAME})
set(CPACK_PROJECT_VERSION ${PROJECT_VERSION})
include(CPack)
|
With find_package https://github.com/libevent/libevent/blob/master/cmake/LibeventConfig.cmake.in#L8 you should be able to just:
find_package(Libevent REQUIRED)
add_executable(TEST-CMAKE main.cpp)
target_link_libraries(TEST-CMAKE libevent::core)
|
73,306,373
| 73,487,207
|
WIX Toolset MSI. How to pass CustomActionData to a CustomAction using WiX if there are several CustomAction and several Properties in the code?
|
I trying using this:
How to pass CustomActionData to a CustomAction using WiX?
I have 2 CA and several Properties. CustomActionData using in second CA.
Product.wxs:
<Binary Id="CustomAction1" SourceFile="..\CustomAction1\bin\Debug\CustomAction1.dll"/>
<Binary Id="BinaryId1" SourceFile="..\CustomAction2\bin\Debug\CustomAction2.dll"/>
<CustomAction Id="CustomAction1" BinaryKey="CustomAction1" Execute="immediate" DllEntry="CustomAction1" />
<CustomAction Id="PrepCustomAction" Property="CustomAction2" Value="PROPERTY1=[NAME];PROPERTY2=[TRUST];PROPERTY3=[LOGIN];PROPERTY4=[PASSWORD];"/>
<CustomAction Id="CustomAction2" BinaryKey="BinaryId1" Execute="deferred" DllEntry="CustomAction2" Return="check" HideTarget="no"/>
<InstallUISequence>
<Custom Action="CustomAction1" After="AppSearch">1</Custom>
<Custom Action="PrepCustomAction" Before="CustomAction2" />
<Custom Action="CustomAction2" Before="InstallFinalize" />
</InstallUISequence>
CustomAction.cpp:
MsiGetProperty(hInstall, TEXT("PROPERTY1;PROPERTY2;PROPERTY3;PROPERTY4;"), buf, &buflen);
I'm expecting the buf to contain properties, but it's empty. What am I doing wrong?
|
Get the value of "CustomActionData" property using MsiGetProperty method. In your case, this method should be called in CustomAction2.
MsiGetProperty(hInstall, TEXT("CustomActionData"), buf, &buflen);
After this, you need to convert returned string into dictionary to get the value of each property.
|
73,307,018
| 73,307,308
|
Token-Pasting Operator pasting "Func_foo" and "(" does not give a valid preprocessing token
|
I am using ## (Token-Pasting Operator) to form a function call.
According to my understanding, a simple example may look like this.
#include <iostream>
#define CALL(x) Func_##x##()
void Func_foo() { std::cout << "Hi from foo()." << std::endl; }
int main() {
std::cout << "Hello World!" << std::endl;
CALL(foo);
return 0;
}
I compiled this code with g++ -std=c++14 -O3 test.cc. The G++ version is 7.3.1.
It returns the following error.
error: pasting "Func_foo" and "(" does not give a valid preprocessing token
If I change the macro to #define CALL(x) Func_##x() (delete the second ##), the error will be solved.
Why the second ## is redundant? The ## connects strings and substitutes with macro arguments if possible. For example, I change the function name to Func_foo1(), then the macro should be #define CALL(x) Func_##x##1(). This works as my expected.
I am a little confused about the macro definition #define CALL(x) Func_##x().
|
A token is the smallest element of a C++ program that is meaningful to the compiler.
The ## Token-pasting operator does not concatenate arbitrary printable characters. It concatenates two tokens into one token.
Why the second ## is redundant?
Because concatenating Func_foo and () does not produce a single token.
|
73,307,166
| 73,307,583
|
Error while trying to overload operator << for all std container printing, why?
|
I am trying to build an operator << overload to print all the standard library container types. So far, the overload works well, but when I use it in a generic program, it breaks when I try to print a simple std::string. In fact, this program:
#include <iostream>
#include <utility>
#include <vector>
#include <map>
#include <string>
// Helper Function to Print Test Containers (Vector and Map)
template <typename T, typename U>
inline std::ostream& operator<<(std::ostream& out, const std::pair<T, U>& p) {
out << "[" << p.first << ", " << p.second << "]";
return out;
}
template <template <typename, typename...> class ContainerType, typename
ValueType, typename... Args>
std::ostream& operator <<(std::ostream& os, const ContainerType<ValueType, Args...>& c) {
for (const auto& v : c) {
os << v << ' ';
}
return os;
}
int main()
{
std::vector <int> v = { 1,2,3 };
std::cout << v;
std::map <int,int> m = { { 1, 1} , { 2, 2 }, { 3, 3 } };
std::cout << m;
std::string s = "Test";
std::cout << s;
}
Gives me this error:
prove.cpp: In function ‘int main()’:
prove.cpp:32:13: error: ambiguous overload for ‘operator<<’ (operand types are ‘std::ostream’ {aka ‘std::basic_ostream<char>’} and ‘std::string’ {aka ‘std::__cxx11::basic_string<char>’})
32 | std::cout << s;
| ~~~~~~~~~ ^~ ~
| | |
| | std::string {aka std::__cxx11::basic_string<char>}
| std::ostream {aka std::basic_ostream<char>}
prove.cpp:16:15: note: candidate: ‘std::ostream& operator<<(std::ostream&, const ContainerType<ValueType, Args ...>&) [with ContainerType = std::__cxx11::basic_string; ValueType = char; Args = {std::char_traits<char>, std::allocator<char>}; std::ostream = std::basic_ostream<char>]’
16 | std::ostream& operator <<(std::ostream& os, const ContainerType<ValueType, Args...>& c) {
| ^~~~~~~~
In file included from /usr/include/c++/9/string:55,
from /usr/include/c++/9/bits/locale_classes.h:40,
from /usr/include/c++/9/bits/ios_base.h:41,
from /usr/include/c++/9/ios:42,
from /usr/include/c++/9/ostream:38,
from /usr/include/c++/9/iostream:39,
from prove.cpp:1:
/usr/include/c++/9/bits/basic_string.h:6419:5: note: candidate: ‘std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&, const std::__cxx11::basic_string<_CharT, _Traits, _Allocator>&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]’
6419 | operator<<(basic_ostream<_CharT, _Traits>& __os,
| ^~~~~~~~
I think that the problem is due to the fact that this overload is used to print also simple std::string objects, but I didn't find any suitable way to solve this so far. Any help? thanks.
|
Your operator<< overload may match types for which an operator<< overload is already defined. I suggest that you disable it for such types:
#include <type_traits>
template <template <typename, typename...> class ContainerType,
typename ValueType, typename... Args>
std::enable_if_t<!is_streamable_v<ContainerType<ValueType, Args...>>,
std::ostream&>
operator<<(std::ostream& os, const ContainerType<ValueType, Args...>& c) {
for (const auto& v : c) {
os << v << ' ';
}
return os;
}
The enable_if_t line uses SFINAE to disable the function for types that are already streamable.
The type trait is_streamable_v that is used above could look like this:
template<class T>
struct is_streamable {
static std::false_type test(...);
template<class U>
static auto test(const U& u) -> decltype(std::declval<std::ostream&>() << u,
std::true_type{});
static constexpr bool value = decltype(test(std::declval<T>()))::value;
};
// helper variable template:
template<class T>
inline constexpr bool is_streamable_v = is_streamable<T>::value;
Your original program should now work as expected:
int main() {
std::vector <int> v = { 1,2,3 };
std::cout << v;
std::map <int,int> m = { { 1, 1} , { 2, 2 }, { 3, 3 } };
std::cout << m;
std::string s = "Test";
std::cout << s;
}
Demo
|
73,308,144
| 73,308,267
|
What exactly happens when we write if(mp.find()==mp.end())
|
I'm currently learning hashmap, I'm facing trouble understanding the iterators, while using it in if statements.
For example,
int main ()
{
std::map<char,int> mymap;
std::map<char,int>::iterator it;
mymap['a']=50;
mymap['b']=100;
mymap['c']=150;
mymap['d']=200;
it = mymap.find('d');
if (it == mymap.end())
mymap.erase (it);
if (it != mymap.end())
mymap.erase (it);
}
I am able to understand what happens in the second if statement. Can anyone explain what exactly does the first if statement will do? When I tried to erase the value of d it does nothing. Can someone explain the difference between the two if statements?
|
From std::map::erase
The iterator pos must be valid and dereferenceable. Thus the end() iterator (which is valid, but is not dereferenceable) cannot be used as a value for pos.
Since the below part of the code fails to comply with the above
if (it == mymap.end())
mymap.erase (it);
the program will have undefined behavior in case it == mymap.end() - which means that it could do just about anything, including nothing or crashing. Avoid undefined behavior like the plague.
The other part is the correct way to do it. Make sure that it is not the end() iterator before using it to erase an element.
if (it != mymap.end())
mymap.erase (it);
Can someone explain the difference between the two if statements?
it = mymap.find('d'); searches for 'd' in the map. If 'd' is found, it returns an iterator to the place in the map where the key 'd' was found. If 'd' is not found, it returns the end() iterator. The end() iterator in all standard containers (possible exception: basic_string), and even plain arrays, isn't dereferenceable. Using an array to illustrate:
int a[] = {7,8,9};
Memory layout:
addr a+0 a+1 a+2 a+3
+---+---+---+---
value | 7 | 8 | 9 | (out of bounds)
+---+---+---+---
^ ^
| |
std::begin(a) std::end(a)
The end() iterator for a plain array points one step after the last element and dereferencing it would mean that you peek out of bounds, with undefined behavior as a result. It's similar for maps, only that the memory layout isn't as simple as for plain arrays.
The difference between the two if statements is therefore that one makes sure that the iterator can be deferenced before using it to erase - and the other makes sure that the iterator is not an iterator that should be deferenced (or used with erase), before using it with erase anyway.
|
73,308,373
| 73,308,374
|
Build message: Cannot open include file: 'msoledbsql.h': No such file or directory
|
My project can't finish build process because I constantly have this error during Visual Studio build: Cannot open include file: 'msoledbsql.h': No such file or directory
I have 'msoledbsql.h' file included in one of the header files.
Does anyone know the solution of this issue?
|
After a long research of this issue I found that I've missing msoledbsql.h file on my machine.
The solution for this is to install Microsoft OLE DB Driver for SQL Server. We can find the driver on official Microsoft site Microsoft OLD DB Driver for SQL Server and choose the one suitable for your system architecture (x64 or x86).
Very important thing during the installation process is to select both options
OLE DB Driver 19 for SQL Server
OLE DB Driver 19 for SQL Server SDK
That should solve the issue.
|
73,308,589
| 73,308,710
|
unordered_map inside C++ class
|
I am writing a simple logging class with C++. I want to create an unordered_map to store logging_levels, but compiling fails.
#include <iostream>
#include <unordered_map>
#include <string>
class logging {
public:
std::unordered_map<std::string, int> m_log_levels;
m_log_levels["info"] = 2;
m_log_levels["warning"] = 1;
m_log_levels["error"] = 0;
private:
int m_level = m_log_levels["info"];
public:
void setLevel(int level) {
m_level = level;
}
void warn(const char* message) {
std::cout << message << std::endl;
}
};
|
You can't put arbitrary code wherever you want in a class definition.
Initialize the hash table in a constructor i.e.
class logging {
public:
std::unordered_map<std::string, int> m_log_levels;
private:
int m_level;
public:
logging() { // <<< this is a constructor...
m_log_levels["info"] = 2;
m_log_levels["warning"] = 1;
m_log_levels["error"] = 0;
m_level = m_log_levels["info"];
}
void setLevel(int level) {
m_level = level;
}
void warn(const char* message) {
std::cout << message << std::endl;
}
};
|
73,308,605
| 73,309,093
|
How to write a Character type concept?
|
The standard library doesn't seem to provide a concept for character types yet. Similar to e.g. std::integral, I want a concept that is suitable for character types (such as char, wchar_t, char32_t, etc.). How should one write a proper concept for this purpose?
Something similar to this could help:
template <typename T>
concept Character = std::integral<T> && sizeof( T ) <= 4;
But I feel like the above is not sufficient. I guess it should have more constraints.
|
template< class T >
concept Character =
/* true if T is same as the listed char types below
* do not forget that e.g. same_as<char, T> is true only
* when T is char and not char&, unsigned char, const char
* or any combination (cvref),
* therefore we only remove the const volatile specifiers
* but not the reference (like in is_integral) */
std::same_as< char, std::remove_cv_t<T> > ||
/* do for each char type,
* see: https://en.cppreference.com/w/cpp/language/types#Character_types */;
Based on the discussion below:
I would say if you introduce a character trait, it would be a good idea to do it like the standard does for e.g. integral types. CV-qualified, signed or unsigned. But not a reference to an integral type, like pointer, which is not that specific type that it points to.
Therefore my suggestion would be a proper (standard conform) type trait for all character types (signed/unsigned, cv-qualified).
To restrict the type of a member variable, there are other methods to achieve that, either through a type constraint (requires) or an assertion (static_assert) or by simply removing the cv-qualifiers.
e.g.
template <Character C>
requires !(std::is_const_v<C> || std::is_volatile_v<C>)
class Foo { static C var = '$'; };
or
template <Character C>
class Foo {
static_assert(
!(std::is_const_v<C> || std::is_volatile_v<C>),
"No cv types allowed."
);
static C var = '$';
};
or
template <Character C>
class Foo {
using char_type = std::remove_cv_t<C>;
static char_type var = '$';
};
|
73,309,210
| 73,309,321
|
Simpler logger function using std::stringstream
|
I'm trying to write a simple logging function which can handle different types in this format:
LOG("This is one type: " << one_type << " and here is a different type: " << diff_type);
I've been looking at the examples here:
How to use my logging class like a std C++ stream?
stringstream with recursive variadic function?
and this is what I came up with:
#include <iostream>
#include <sstream>
void LOG(std::stringstream& ss)
{
std::cout << ss.str() << std::endl;
}
However, even when I just do:
LOG("Some text");
I get the error:
could not convert ‘(const char*)"Some text"’ from ‘const char*’ to ‘std::stringstream’ {aka ‘std::__cxx11::basic_stringstream<char>’}
How can I implement this?
|
A common way to solve this is to make LOG a macro that just does text substitution instead. You could define a LOG macro like
#define LOG(to_log) \
do \
{ \
std::cout << to_log << std::endl; \
} while (false)
and then
LOG("This is one type: " << one_type << " and here is a different type: " << diff_type);
would get expanded to
do
{
std::cout << "This is one type: " << one_type << " and here is a different type: " << diff_type << std::endl;
} while (false);
|
73,309,470
| 73,309,768
|
Use minitrace in a given namespace in C++
|
I'm using minitrace to profile performance of my functions in a namesapce filtration. However, minitrace does not work if functions like MTR_BEGIN() are invoked inside a namespace. The following is my code. My idea is to add namesapce to minitrace.h. Any suggestion on having minitrace work in a namesapce?
#include "minitrace.h"
namesapce filtration {
FILE* trace_file = fopen("/tmp/trace", "wb");
mtr_init_from_stream(trace_file);
MTR_META_PROCESS_NAME("minitrace_test");
MTR_META_THREAD_NAME("main thread");
int long_running_thing_1;
int long_running_thing_2;
MTR_START("background", "long_running", &long_running_thing_1);
MTR_START("background", "long_running", &long_running_thing_2);
MTR_BEGIN("main", "binary_search");
binarySearch();
MTR_END("main", "binary_search");
MTR_FINISH("background", "long_running", &long_running_thing_1);
MTR_FINISH("background", "long_running", &long_running_thing_2);
mtr_flush();
mtr_shutdown();
}
|
I see some functions signature in minitrace.h. I think you can add namesapce like minitrace to these functions.
|
73,309,661
| 73,334,474
|
How to interpret complex strings as graph properties when reading a graphML file using `boost::read_graphml`?
|
I have a graph type where each Vertex carries a std::vector<int> as a property.
struct VertexProperties {
std::vector<int> numbers;
};
using Graph = boost::adjacency_list<
boost::vecS, boost::vecS, boost::undirectedS, VertexProperties>;
I wrote an example object of my graph type to a GraphML file using boost::write_graphml. To do so, I used boost::make_transform_value_property_map to convert the std::vector<int> property to a std::string. The GraphML file has the following contents:
<?xml version="1.0" encoding="UTF-8"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
<key id="key0" for="node" attr.name="numbers" attr.type="string" />
<graph id="G" edgedefault="undirected" parse.nodeids="free" parse.edgeids="canonical" parse.order="nodesfirst">
<node id="n0">
<data key="key0">1 2 3 </data>
</node>
</graph>
</graphml>
Now I would like to read the file back in to reobtain the graph (in a different program) using boost::read_graphml. To do so, it is necessary to create a boost::dynamic_properties object and add to that a property map that can understand the information found in the GraphML file and set the correct vertex property accordingly.
How can the latter property map be defined?
|
I solved my problem by writing a custom property map class template TranslateStringPMap that wraps an existing property map and takes two function objects that convert between strings and the wrapped map's value type.
File translate_string_pmap.hpp:
#ifndef TRANSLATE_STRING_PMAP_H
#define TRANSLATE_STRING_PMAP_H
#include <string>
#include <boost/property_map/property_map.hpp>
template <typename PMap, typename ToString, typename FromString>
class TranslateStringPMap {
public:
using category = boost::read_write_property_map_tag;
using key_type = typename boost::property_traits<PMap>::key_type;
using reference = std::string;
using value_type = std::string;
TranslateStringPMap(
PMap wrapped_pmap, ToString to_string, FromString from_string)
: wrapped_pmap{wrapped_pmap},
to_string{to_string},
from_string{from_string} {}
auto friend get(TranslateStringPMap const& translator, key_type const& key)
-> value_type {
return translator.to_string(get(translator.wrapped_pmap, key));
}
auto friend put(
TranslateStringPMap const& translator, key_type const& key,
value_type const& value) -> void {
boost::put(translator.wrapped_pmap, key, translator.from_string(value));
}
private:
PMap wrapped_pmap;
ToString to_string;
FromString from_string;
};
#endif
By customizing the conversion function objects to_string and from_string, TranslateStringPMap can be added to a boost::dynamic_properties object to facilitate reading and writing of arbitrary graph property types. The following file gives a usage example.
File graph_rw.cpp:
#include <sstream>
#include <string>
#include <vector>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graphml.hpp>
#include <boost/property_map/dynamic_property_map.hpp>
#include "translate_string_pmap.hpp"
struct VertexProperties {
std::vector<int> numbers;
};
using Graph = boost::adjacency_list<
boost::vecS, boost::vecS, boost::undirectedS, VertexProperties>;
auto vec2str(std::vector<int> const& vec) -> std::string {
auto str = std::string{};
for (auto number : vec) {
str += std::to_string(number) += " ";
}
return str;
}
auto str2vec(std::string const& str) -> std::vector<int> {
auto strs = std::stringstream{str};
auto number = 0;
auto vec = std::vector<int>{};
while (strs >> number) {
vec.push_back(number);
}
return vec;
}
auto write_my_graphml(Graph& graph, std::ofstream& output_stream) -> void {
auto dprops = boost::dynamic_properties{};
dprops.property(
"numbers",
TranslateStringPMap{
boost::get(&VertexProperties::numbers, graph), vec2str, str2vec});
boost::write_graphml(output_stream, graph, dprops);
}
auto read_my_graphml(std::ifstream& input_stream) -> Graph {
auto graph = Graph{};
auto dprops = boost::dynamic_properties{};
dprops.property(
"numbers",
TranslateStringPMap{
boost::get(&VertexProperties::numbers, graph), vec2str, str2vec});
boost::read_graphml(input_stream, graph, dprops);
return graph;
}
auto main() -> int {
{
auto graph1 = Graph{};
boost::add_vertex(VertexProperties{{1, 2, 3}}, graph1);
auto out_stream = std::ofstream{"graph1.gml"};
write_my_graphml(graph1, out_stream);
}
{
auto in_stream = std::ifstream{"graph1.gml"};
auto graph2 = read_my_graphml(in_stream);
auto out_stream = std::ofstream{"graph2.gml"};
write_my_graphml(graph2, out_stream);
}
}
|
73,309,856
| 73,310,537
|
Why copy intialisation is used instead of direct initialisation when passing argument to function parameter by value
|
I am learning C++ using the resources listed here. In particular, I came to know that copy initialization is used when passing arguments to function parameters(by value) etc.
For example, from decl.init.general#14:
The initialization that occurs in the = form of a brace-or-equal-initializer or condition ([stmt.select]), as well as in argument passing, function return, throwing an exception ([except.throw]), handling an exception ([except.handle]), and aggregate member initialization ([dcl.init.aggr]), is called copy-initialization.
(emphasis mine)
My question is that is there is reason for using copy initialization instead of direct initialization when passing argument to function parameters(by value)?
To make the question more concise, lets look at a contrived example:
struct C
{
explicit C(int)
{
}
};
void func(C param)
{
}
int main()
{
C s1(2); //#1: this works, direct-initialization and so explicit ctor can be used
C s2 = 2; //#2: won't work, copy-initialization and so explict ctor cannot be used here
func(2); //#3: won't work, copy-initialization of parameter param and so explict ctor cannot be used here
return 0;
}
As we can see in the above example, the function call func(2) won't work because here the parameter param is copy initialized instead of direct initialized and so the explicit constructor C::C(int) cannot be used.
Summary
My question is why does the C++ standard(committee) choose to copy initialize the parameter param instead of direct initializing the parameter using the passed argument 2. I mean if param was direct initialized then the call func(2) would've succeeded.
Maybe there is a reason, like advantages of using copy initializing the parameter instead of direct initializing it or maybe there are disadvantages of using direct initializing the parameter instead of copy initializing it.
|
It is precisely so that this does not work.
The whole point of the distinction between copy-initialization and direct-initialization is to prevent implicit conversions in cases of copy-initialization. By using explicit in your constructor, you are declaring that you do not want integers to be converted to C unless the user spells it out directly.
When you attempt to call func(2), the type C is not explicitly visible anywhere near the call site. Therefore, it should be copy-initialization and if C's conversion constructor from int is explicit, the call should be disallowed.
|
73,310,337
| 73,310,415
|
While I want to use the data members from .h file to the other file
|
I am using the two .h files and the two .cpp file.
The employee.h file contains
class Employee
{
public:
std::string Name,Id,Address;
};
The second .h file stack.h contains
#include "employee.h"
class Stack
{
public:
int total=0;
void push();
void pop();
void display();
};
The first.cpp file stack.cpp contains
#include "stack.h"
Employee obj1;
Stack emp[10];
void Stack::push()
{
if(total>=10)
{
total--;
std::cout <<"Stack is Overflowed";
}
else
{
std::cout<<"Enter data of employee "<<std::endl;
std::cout<<"Enter employee name: ";
std::cin>>emp[total].obj1.Name;
std::cout<<"Enter id: ";
std::cin>>emp[total].obj1.Id;
std::cout<<"Enter address: ";
std::cin>>emp[total].obj1.Address;
}
total++;
}
The second cpp file main.cpp contains
#include "stack.h"
Stack obj;
int main()
{
obj.push();
}
While i am executing above files it is giving an error like this
g++ stack.cpp main.cpp
stack.cpp: In member function ‘void Stack::push()’:
stack.cpp:16:25: error: ‘class Stack’ has no member named ‘obj1’
std::cin>>emp[total].obj1.Name;
^~~~
stack.cpp:18:26: error: ‘class Stack’ has no member named ‘obj1’
std::cin>>emp[total].obj1.Id;
^~~~
stack.cpp:20:26: error: ‘class Stack’ has no member named ‘obj1’
std::cin>>emp[total].obj1.Address;
If i remove the obj1 from stack.cpp then it will giving an error like this
code:
std::cout<<"Enter data of employee "<<std::endl;
std::cout<<"Enter employee name: ";
std::cin>>emp[total].Name;
std::cout<<"Enter id: ";
std::cin>>emp[total].Id;
std::cout<<"Enter address: ";
std::cin>>emp[total].Address;
Error:
g++ stack.cpp main.cpp
stack.cpp: In member function ‘void Stack::push()’:
stack.cpp:16:25: error: ‘class Stack’ has no member named ‘Name’
std::cin>>emp[total].Name;
^~~~
stack.cpp:18:26: error: ‘class Stack’ has no member named ‘Id’
std::cin>>emp[total].Id;
^~
stack.cpp:20:26: error: ‘class Stack’ has no member named ‘Address’
std::cin>>emp[total].Address;
Can anyone please help to this problem?
|
It seems to me that you are trying to create stack of employees. The way to do this is to put the employees inside the Stack. Like this
class Employee
{
public:
std::string Name,Id,Address;
};
class Stack
{
public:
int total=0;
Employee emp[10]; // 10 employees
void push();
void pop();
void display();
};
void Stack::push()
{
std::cout<<"Enter data of employee "<<std::endl;
std::cout<<"Enter employee name: ";
std::cin>>emp[total].Name;
std::cout<<"Enter id: ";
std::cin>>emp[total].Id;
std::cout<<"Enter address: ";
std::cin>>emp[total].Address;
}
You already did this right with total, it's just the same for everything else that you want to be part of a Stack.
|
73,311,181
| 73,311,410
|
Explicit instantiation unexpected behavior - breaking ODR does not cause compilation errors
|
Let's consider the following code:
output_data.hpp
#pragma once
#include <functional>
#include <cstddef>
namespace example {
using Callback = std::function<void(int)>;
struct OutputData {
void * data = nullptr;
std::size_t size = 5;
Callback callback = nullptr;
};
} // namespace example
buffer.hpp
#pragma once
#include <vector>
namespace example {
template <typename T>
struct Buffer {
Buffer(std::size_t size);
std::vector<T> buffer_;
};
} // namespace example
buffer.cpp
#include "buffer.hpp"
#include "output_data.hpp"
namespace example {
template <typename T>
Buffer<T>::Buffer(std::size_t size) : buffer_(size)
{
}
template struct Buffer<OutputData>;
} // namespace example
main.cpp
#include <iostream>
#include <memory>
#include <functional>
#include "buffer.hpp"
namespace example {
using Callback = std::function<void(int)>;
struct OutputData {
Callback callback = nullptr;
};
}
int main() {
std::shared_ptr<int> ptr = std::make_shared<int>(5);
example::Buffer<example::OutputData> buf(3);
example::Callback simple_callback = [=](int a) {
std::cout << a << *ptr << "\n";
};
buf.buffer_[1].callback = simple_callback;
}
[Godbolt][https://godbolt.org/z/EEzE7oerb]
The compilation ends without errors, while the execution ends with Segmentation Fault. Segfault is caused by the fact that in main.cpp I used a different struct than the one in buffer.cpp during explicit instantiation. Why was the code compiled without errors?
Is it possible to detect such programming mistakes during compilation? Is there any warning flag for detecting such cases ?
|
Why was the code compiled without errors?
Credit to Richard Critten's comment for the source.
"The compiler is not required to diagnose this violation, but the behavior of the program that violates it is undefined"
Is it possible to detect such programming mistakes during compilation?
Yes, see below.
Is there any warning flag for detecting such cases ?
Your ODR violation does not exist during compilation of any single source file. It only exists during (after) linking.
g++ will, unless disabled, warn of ODR violations during link time if Link Time Optimization is enabled with the flag -flto
[Godbolt]
|
73,311,378
| 73,324,817
|
Wxsmith how to make WxGrid infinite rows
|
I want to keep writing data into WxGrid, but i need to set the rows for WxGrid. I've searched some way but the answer that i get is to use Wx.GridTableBase which is for WxPython.
Is there any way to make WxGrid rows infinite?
I'm using codeblocks c++ with WxSmith.
|
Okay so i just need to use AppendRows() everytime i need to add rows. it's on the manuals https://docs.wxwidgets.org/3.0/classwx_grid.html
|
73,311,661
| 73,314,450
|
Errors in creating a Webview2 sample app in UWP
|
I am following the steps mentioned here and am able to successfully create the sample app sans webview till Step 5. From Step6 onwards, things go wrong.
This is the current content of my MainPage.xaml:
<Page
x:Class="Webview2.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Webview2"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:controls="using:Microsoft.UI.Xaml.Controls"
mc:Ignorable="d">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
<Button x:Name="myButton" Click="ClickHandler">Click Me</Button>
</StackPanel>
</Page>
I added this block
xmlns:controls="using:Microsoft.UI.Xaml.Controls"
as well as
<controls:WebView2 x:Name="WebView2" Source="https://bing.com"/>
inside the StackPanel, with the XAML now looking like
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
<!--<Button x:Name="myButton" Click="ClickHandler">Click Me</Button>-->
<controls:WebView2 x:Name="WebView2" Source="https://bing.com"/>
</StackPanel>
This is what I see in the design editor
and upon building I encounter a lot of errors like
error C3083: 'Microsoft': the symbol to the left of a '::' must be a type (compiling source file MainPage.cpp)
error C3083: 'UI': the symbol to the left of a '::' must be a type (compiling source file MainPage.cpp)
error C3083: 'Xaml': the symbol to the left of a '::' must be a type (compiling source file MainPage.cpp)
error C3083: 'Controls': the symbol to the left of a '::' must be a type (compiling source file MainPage.cpp)
error C3646: 'WebView2': unknown override specifier (compiling source file MainPage.cpp)
essentially complaining about the usage of Microsoft in ::winrt::Microsoft::UI::Xaml::Controls::WebView2
I'm not sure what's exactly going wrong and can't find something similar to my issue. Would anybody know what's missing/needs to be changed to get the sample working?
|
Errors in creating a Webview2 sample app in UWP
As Raymond Chen points out the code is failing to include the C++/WinRT projection headers for Microsoft::UI::Xaml::Controls. After installing the NuGet package, please go to pch.h and add the following #include directives. For more info you could refer to A basic C++/WinRT Windows UI Library 2 example (UWP) document.
#include "winrt/Microsoft.UI.Xaml.Automation.Peers.h"
#include "winrt/Microsoft.UI.Xaml.Controls.h"
#include "winrt/Microsoft.UI.Xaml.Controls.Primitives.h"
#include "winrt/Microsoft.UI.Xaml.Media.h"
#include "winrt/Microsoft.UI.Xaml.XamlTypeInfo.h"
|
73,312,460
| 73,312,539
|
Crash when erasing element from unordered_set in loop
|
I have some code that tries to erase certain elements from an unordered_set. It is done in a loop. The crash happens after it removes the first element found. I currently don't have any other setup except an M1 Mac. The crash happens there but doesn't on online sites (such as Coliru). I am wondering if my code has any undefined behavior. Comments are welcome. Thanks a lot!
#include <unordered_set>
#include <iostream>
struct Point {
int x;
int y;
};
bool operator==(const Point& p1, const Point& p2)
{
return p1.x == p2.x && p1.y == p2.y;
}
struct PointHash
{
std::size_t operator() (const Point& p) const {
return std::hash<int>()(p.x) ^ std::hash<int>()(p.y);
}
};
int main()
{
std::unordered_set<Point, PointHash> S{Point{0,1}, Point{1,1}, Point{1,0}, Point{2,0}};
for (auto it = S.begin(); it != S.end(); ++it) {
if (it->x == 0)
it = S.erase(it);
}
for (auto&& p: S)
std::cout << p.x << ',' << p.y << std::endl;
}
Please not that I also tried for-range on the erase loop but got the same crash.
|
Rewrite the for loop like
for (auto it = S.begin(); it != S.end(); ) {
if (it->x == 0)
it = S.erase(it);
else
++it;
}
If the compiler supports C++ 20 then you can just write
std::erase_if( S, []( const auto &p ) { return p.x == 0; } );
Here is a demonstration program
#include <unordered_set>
#include <iostream>
struct Point {
int x;
int y;
};
bool operator==(const Point& p1, const Point& p2)
{
return p1.x == p2.x && p1.y == p2.y;
}
struct PointHash
{
std::size_t operator() (const Point& p) const {
return std::hash<int>()(p.x) ^ std::hash<int>()(p.y);
}
};
int main()
{
std::unordered_set<Point, PointHash> S{Point{0,1}, Point{1,1}, Point{1,0}, Point{2,0}};
for ( const auto &p : S )
std::cout << p.x << ',' << p.y << std::endl;
std::cout << '\n';
std::erase_if( S, []( const auto &p ) { return p.x == 0; } );
for ( const auto &p : S)
std::cout << p.x << ',' << p.y << std::endl;
}
The program output is
2,0
1,1
1,0
0,1
2,0
1,1
1,0
|
73,312,547
| 73,314,719
|
Why can't structure initialization work with array of char?
|
When initializing a struct using curly braces, it does not seem to work with an array of chars. I can write an equivalent constructor that works below. Is there any syntax so I don't have to write the constructor?
#include <cstdint>
#include <cstring>
using namespace std;
struct NamedLocationData {
uint16_t offset;
char stateName[21];
float lat;
float lon;
uint32_t population;
NamedLocationData(uint16_t offset, const char stateName[21],
float lat, float lon, uint32_t population)
: offset(offset), lat(lat), lon(lon), population(population) {
strncpy(this->stateName, stateName, 21);
}
};
int main() {
uint16_t nameOffset = 0;
char stateName[21] = "New York";
float lat = 40;
float lon = -74;
uint32_t population = 8000000;
#if 0
NamedLocationData temp = NamedLocationData
{
nameOffset, stateName, lat, lon, population
};
#endif
NamedLocationData temp( nameOffset, stateName, lat, lon, population);
}
|
Default constructors are one of the special member functions. If no constructors are declared in a class, the compiler provides an implicit inline default constructor.
I suggest you change char[] to string so that stateName will be able to get a value.
#include <cstdint>
#include <cstring>
#include <string>
using namespace std;
struct NamedLocationData {
uint16_t offset;
string stateName;
float lat;
float lon;
uint32_t population;
NamedLocationData(uint16_t offset, string stateName,
float lat, float lon, uint32_t population)
: offset(offset), lat(lat), lon(lon), population(population) ,
stateName(stateName){}
};
int main() {
uint16_t nameOffset = 0;
string stateName = "New York";
float lat = 40;
float lon = -74;
uint32_t population = 8000000;
#if 0
NamedLocationData temp = NamedLocationData
{
nameOffset, stateName, lat, lon, population
};
#endif
NamedLocationData temp(nameOffset, stateName, lat, lon, population);
return 0;
}
Result:
|
73,312,585
| 73,313,532
|
C++ unicode strings - the basic_strings know nothing about Unicode?
|
I see here that the C++ standard library now has typedefs of std::basic_string like u8string and u16string, but I don't see any member functions or algorithms that know much of anything about Unicode.
Let's say I want to iterate over the "grapheme clusters" in a string stored as UTF-8. These are the things that humans view as "characters", even though they may be multiple bytes or even multiple 32bit code units (like emoji flags ). Am I right that std::u8string has nothing for that and I need to use a library like ICU?
It appears the substr member function would split a UTF-8 or UTF-16 character in half, so again I need to use ICU or something to make sure I don't do that.
Correct?
|
Am I right that std::u8string has nothing for that and I need to use a library like ICU?
It appears the substr member function would split a UTF-8 or UTF-16 character in half, so again I need to use ICU or something to make sure I don't do that.
Yes, you are correct, on both counts. The standard C++ library has no concept of Unicode codepoints/graphemes, only of encoded codeunits stored in individual char/wchar_t/char16_t/char32_t elements of strings.
|
73,312,652
| 73,312,796
|
How to setup complex project with Visual Studio 2022?
|
I have project that I was developing for years in Linux.
It depends on MKL, libxml++, GSL and armadillo library.
Its installation structure is done in CMake and project is formed by building a shared library and couple of executables that link to it. There are about 20 classes in the library.
Project structure is:
--src
--executable1.cpp
--executable2.cpp
--mysharedlib
--class1.h
--class1.cpp
--...
My question is how to install and run this code in Visual Studio in Windows.
I never used VS before and am still going through tutorials. I managed to run my code by installing Ubuntu on WSL, but I I'd like a VS solution as it'd be handy to pass to user not familiar with Linux.
I tried opening the project directory with VS, hoping CMAKE would do all the magic, but expectedly it cannot locate the dependent libraries, so I am now going through web looking how to integrate each to VS. I managed to find armadillo and mkl guide, but I am lost on how to link these libraries to my project codes and whether I should abandon its current cmake setup and start building the code structure differently in VS.
Any links to useful VS tutorials and advices how to this are greatly appreciated.
|
VS does have support for CMake, although I have no idea how well VS integrates CMake. If you're not set on using VS, you might want to look into an IDE that uses CMake at it's core, Clion comes to mind. That being said, when coming from Linux you don't have the (initial) luxury of simply installing all the dependencies via a preinstalled package manager.
In order for CMake to find your dependencies (assuming you've configured them by using find_package()) you should add the sources of your dependencies to your project in a thirdparty folder (name is up to you) and add these dependencies using add_subdirectory() instead. This will compile all your dependencies from source, so you might have to configure these dependencies yourself (look into the documentation of your dependencies on how to build them from source).
Another way is to use a package manager that is available on Windows to download, compile and provide your dependencies to your build tools. vcpkg comes to mind, claiming to integrate well with CMake by providing a toolchain file that you can pass to CMake when building your project. You might even be able to configure VS to automatically pass this toolchain to CMake whenever it's invoked.
From personal experience, there is no need to convert an existing project to the VS project structure. There's plenty of available solutions and tools available on Windows to work with CMake projects. Going with the cross-platform approach should be preferred unless you're only targeting Windows, using VS to it's fullest then might give you some additional quality of life.
If you have more specific questions regarding this, I suggest that you update your original post or to create separate, specific questions regarding the processes involved in setting up an existing CMake project on Windows.
|
73,312,795
| 73,312,879
|
How do you transpose a tensor in LibTorch?
|
I can't seem to figure out how to transpose a tensor in LibTorch, the (C++ version of PyTorch).
torch::Tensor one_T = torch::rand({6, 6});
int main() {
std::cout << one_T.transpose << "\n";
}
My error...
/home/iii/tor/m_gym/multiv_normal.cpp:53:24: note: mismatched types ‘const std::set<Types ...>’ and ‘at::Tensor (at::Tensor::*)(at::Dimname, at::Dimname) const’
53 | std::cout << one_T.transpose << "\n";
| ^~~~~~~~~
/home/iii/tor/m_gym/multiv_normal.cpp:53:24: note: mismatched types ‘const std::set<Types ...>’ and ‘at::Tensor (at::Tensor::*)(int64_t, int64_t) const’ {aka ‘at::Tensor (at::Tensor::*)(long int, long int) const’}
In file included from /home/iii/tor/m_gym/libtorch/include/c10/util/Logging.h:28,
from /home/iii/tor/m_gym/libtorch/include/c10/core/TensorImpl.h:17,
from /home/iii/tor/m_gym/libtorch/include/ATen/core/TensorBody.h:20,
from /home/iii/tor/m_gym/libtorch/include/ATen/core/Tensor.h:3,
from /home/iii/tor/m_gym/libtorch/include/ATen/Tensor.h:3,
from /home/iii/tor/m_gym/libtorch/include/torch/csrc/autograd/function_hook.h:3,
from /home/iii/tor/m_gym/libtorch/include/torch/csrc/autograd/cpp_hook.h:2,
from /home/iii/tor/m_gym/libtorch/include/torch/csrc/autograd/variable.h:6,
|
one_T.transpose(0, 1)
The 0, 1 is the type of default transpose used in PyTorch and Numpy without being specified.
|
73,312,905
| 73,313,089
|
dllexport a type with a std container of std::unique_ptr results in error C2280
|
I'm trying to dllexport a type with a std container of std::unique_ptr member, f.e.
struct __declspec(dllexport) C {
std::vector<std::unique_ptr<int>> c_;
};
but whatever i try, msvc always complains about
msvc/14.33.31629/include\xutility(4145): error C2280: 'std::unique_ptr<int,std::default_delete<int>> &std::unique_ptr<int,std::default_delete<int>>::operator =(const std::unique_ptr<int,std::default_delete<int>> &)': attempting to reference a deleted function
The container type doesn't matter; the error is almost identical (always C2280) for vector, map, and others.
However, as soon as a std::unique_ptr member is added to the type, f.e.
struct __declspec(dllexport) C {
std::vector<std::unique_ptr<int>> c_;
std::unique_ptr<int> rup;
};
the error disappears.
I have no clue if this is the intended behavior, what causes this problem and how it can be fixed without adding a random std::unique_ptr member. What am i missing?
Demo
|
When you have a member std::vector<std::unique_ptr<int>> c_;, the compiler will provide a copy assignment operator C& operator=(const C&) that will try to copy the c_ member. This will fail to compile if it is actually used, since the elements of c_ can't be copied.
__declspec(dllexport) seems to try to create this implicitly-declared function (maybe to export it? Though it doesn't seem to actually do that), which fails.
When you add std::unique_ptr<int> rup;, this is a type without a copy constructor at all, so the implicit operator=(const C&) is suppressed (The move assign operator C& operator=(C&&) can still be used).
You can get rid of the implicit copy-assign operator by declaring a move-assign operator or a move constructor:
struct __declspec(dllexport) C {
std::vector<std::unique_ptr<int>> c_;
C(C&&) = default;
};
Or by inheriting from a move-only type/having a move-only member:
struct move_only { constexpr move_only(move_only&&) noexcept = default; };
struct __declspec(dllexport) C : private move_only {
std::vector<std::unique_ptr<int>> c_;
};
|
73,313,073
| 73,315,313
|
CS50 Week5 Speller compiles but is incorrect. Also takes no time on size and unload
|
I started working on this yesterday. It compiles but whenever I run it with
./speller texts/lalaland.txt
I get this result:
WORDS MISSPELLED: 17134
WORDS IN DICTIONARY: 143091
WORDS IN TEXT: 17756
TIME IN load: 0.04
TIME IN check: 8.41
TIME IN size: 0.00
TIME IN unload: 0.00
TIME IN TOTAL: 8.45
As you can see it takes a stupid amount of time in "check" and no time in "size" or "unload". I'm almost certain there's nothing wrong with my check function though. Any assistance would be appreciated.
// Implements a dictionary's functionality
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <stdbool.h>
#include <cs50.h>
#include <stdio.h>
#include "dictionary.h"
#include <strings.h>
unsigned int counter;
unsigned int i;
// Represents a node in a hash table
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
// TODO: Choose number of buckets in hash table
const unsigned int N = 26;
// Hash table
node *table[N];
// Returns true if word is in dictionary, else false
bool check(const char *word)
{
i = hash(word);
node *cursor = table[i];
while (cursor != 0)
{
if (strcasecmp(cursor->word, word) == 0)
{
return true;
}
cursor = cursor->next;
}
return false;
}
// Hashes word to a number
unsigned int hash(const char *word)
{
int value;
for (int j = 0; j< strlen(word); j++)
{
value = value + tolower(word[j]);
}
return (value % N);
}
// Loads dictionary into memory, returning true if successful, else false
bool load(const char *dictionary)
{
// TODO
FILE* file = fopen(dictionary, "r");
if (file == NULL)
{
return false;
}
char word[LENGTH + 1];
while (fscanf(file, "%s", word) != EOF)
{
node *new = malloc(sizeof(node));
if (new == NULL)
{
return false;
}
strcpy(new->word, word);
new->next = NULL;
i = hash(word);
new->next = table[i];
table[i] = new;
counter++;
}
fclose(file);
return true;
}
// Returns number of words in a dictionary if loaded, else 0 if not yet loaded
unsigned int size(void)
{
if (counter != 0)
{
return counter;
}
return 0;
}
// Unloads dictionary from memory, returning true if successful, else false
bool unload(void)
{
for (int j = 0; j < N; j++)
{
node *head = table[j];
node *cursor = head;
node *temp = head;
while(cursor != NULL)
{
cursor = cursor->next;
free(temp);
temp = cursor;
}
if (cursor == NULL)
{
return true;
}
}
return false;
}
|
There is a problem with the hash function. valgrind will complain about an unitialised value in hash; specifically value. Because value is not initialized, it will have the value that is stored in the memory that is assigned to it. Unpredictable results ensue.
There is also a problem with unload. Once the first node is freed, program will return true from the unload function. However, it hasn't freed any other nodes.
|
73,313,128
| 73,313,377
|
Automatically declare member pointers to their own classes
|
My question is:
Is there a way to declare static member pointers to their own classes automatically?
I have a C++ state machine, in which classes have static pointers to their own classes. This means I can bind a given object to the pointer in its class uniquely. In other words, from each class, only 1 instance can be bound to the static pointers, which pointers then can be used to select from the pool of instances the one that is currently bound.
class A {
public:
static A *ptr;
void bind() { ptr = this; }
}
class B {
public:
static B *ptr;
void bind() { ptr = this; }
}
To me this seems like there has to be some way to abstract this. The process in each class is basically the same: a static pointer to the class and a bind function to assign this to said pointer. (I'm aware of the dangers regarding the lifetimes of each particular bound object, consider this taken care of.)
As far as I know, these type of abstractions are usually performed with inheritance, however I can't seem to find a way to abstract out the type of ptr in a hierarchy, or using template classes.
The optimal solution would be one that doesn't need any information from the programmer regarding the type of ptr in any of the classes, since it seems to be available information at compile time.
Can this be done? Can it be avoided to explicitly declare ptr in each class and automate the process?
This is the closes I got to a solution, but did not succeed: C++ - Are there ways to get current class type with invariant syntax?
Thank you in advance!
|
The only thing I can think of would be a CRTP-based approach, something like:
template<typename T> struct current_instance {
static T *ptr;
void bind() { ptr = static_cast<T *>(this); }
};
// ...
template<typename T> T *current_instance<T>::ptr;
//--------------------------------------------------------------
class A : current_instance<A> {
// ...
};
class B : current_instance<B> {
// ...
};
|
73,313,430
| 73,313,445
|
How to track mouse dragging?
|
What event do I need to write in my wxWidgets program so that I can track mouse dragging.
I mean hold down the left mouse button and track the movement while it is pressed.
|
Bind(wxEVT_MOTION, [&](wxMouseEvent& event) {
if (event.Dragging()) {
if (event.LeftIsDown()) {
// code
}
}
});
|
73,313,543
| 73,313,582
|
Is there a way to get rid of template <class T> on operator overloading?
|
I would like to know if there is a way to get rid of template <class TI> to make my code more clear (I have an overload for every logic operator, not only operator==). Only in C++98, please.
template <class T>
class iter
{
public:
// some stuff
private:
template <class TI>
friend bool operator == (const iter<TI> &lhs, const iter<TI> &rhs);
};
template <class T>
bool operator == (const iter<T> &lhs, const iter<T> &rhs) {
return (lhs._ptr == rhs._ptr);
}
|
Within template<class T> class iter, you may simply use iter to mean iter<T>.
template <class T>
class iter
{
public:
// some stuff
private:
friend bool operator == (const iter& lhs, const iter& rhs);
{
return (lhs._ptr == rhs._ptr);
}
};
|
73,313,547
| 73,313,568
|
C++ Passing a template function to another function without specifying the template parameter
|
Intro
Two weeks ago I started a new project and came along another idea for a project: a test runner for automating tests of template functions - which I'm currently working on.
The main reason behind all that is that I want to
learn more about (modern) C++ and
implement some stuff from my uni lectures.
Said test runner should be able to test a template function, i.e.:
// Said template function (*)
template <class T>
T add(T a, T b) {
return a + b;
}
Setup Explanation
In order to do so I created a class TestRunner (shown in the following) that gets a tuple of parameters via its constructor and has a friend (run(...)) that executed the test.
template <class... PS>
class TestRunner {
public:
// constructors
explicit TestRunner(std::tuple<PS...> paramSetTuple) : paramSets_(paramSetTuple) {}
// ... other unimportant stuff ...
// friends
template <size_t idx, typename F, class... P>
friend constexpr void run(TestRunner<P...> testRunner, F&& testFunc, std::string_view testFuncName);
private:
std::tuple<PS...> paramSets_;
};
As seen here run(...) gets the an instance of TestRunner, a rvalue reference to the function that shall be tested and some string for a better console output.
(just FYI, but not important to the problem itself: The reason for making this friend function is that I want to implement different tests and I don't want to just copy paste the basic functionality behind run(...) as well as I want to created a macro that spares me of the run(...)'s last argument.)
Finally, the problem itself:
I want to be able to pass add(...) to run(...) without specifying add(...)'s template parameter, because this template parameter should be specified automatically when I use the add(...) function in run(...), which looks like this:
template <size_t idx = 0, typename F, ParameterSetConcept... P>
constexpr void run(TestRunner<P...> testRunner, F&& testFunc, std::string_view testFuncName) {
// ... some stuff to iterate through the tuple ...
// ... some other stuff to get the input parameters for add(...) and it's expected output
// for now, let's just say the input is a tuple i.e. testInputs,
// and the expected output i.e. expectedOutput
auto output = std::apply(std::forward<F>(testFunc), testInputs;
if ( output == expectedOutput ) {
// this == is just an example for a successful test
// (more options will be implemented later)
run<idx + 1>(testRunner, std::forward<F>(testFunc), testFuncName);
} else {
// ... some error output ...
}
}
It be said that the iteration through tuples, and fetching of the tuple testInputs as well as the expected output expextedOutput work just fine.
Now what I need is to be able to call run(...) in the main (or a gtest) without specifying it's template parameter.
This may look something like this:
int main() {
TestRunner testRunner(...); // init testRunner as it's supposed to be
run(testRunner, add, "add");
return 0;
}
Is there even a solution to this problem?
In advance: THANKS FOR ANY HELP!
Last Comments
I'm aware that the total setup of using such a 'complex' construct in a UnitTest as I mentioned before (gtest) might be a bad idea for the UnitTest concept itself, but I mainly do all this because I want to learn something about C++ and came along this problem.
Please don't judge ^^ I know that there is a option for value parameterized tests and even type parameterized tests in the gtest framework.
|
The closest thing I can think of is,
auto call_add = [](auto&&... args){ return add(std::forward<decltype(args)>(args)...); };
doSomethingWithAdd(call_add);
Of course, you can add a macro for it if it's too complicated.
|
73,313,854
| 73,313,995
|
Code not compiling when template functions are placed in a certain order
|
The following program compiles successfully.
template<typename T>
T sum(T x) {
return x;
}
template<typename T, typename... Args>
T sum(T x, Args... args) {
return x + sum(args...);
}
int main() {
sum(1, 2, 3, 4, 5);
}
However, when I switch the order in which the template functions are written, it no longer compiles:
template<typename T, typename... Args>
T sum(T x, Args... args) {
return x + sum(args...);
}
template<typename T>
T sum(T x) {
return x;
}
int main() {
sum(1, 2, 3, 4, 5);
}
The compiler error I get is:
error C2780: 'T sum(T,Args...)': expects 2 arguments - 0 provided, message : see declaration of 'sum'
Why does this happen? Aren't both functions already defined prior to being called in main()? Why does the order in which they're written in matter?
|
At the heart of your question is the following issue: when a function name, such as sum, appears inside a function template, what function does it refer to?
You wrote:
Aren't both functions already defined prior to being called in main()? Why does the order in which they're written in matter?
You seem to have the following expectation: that when a function template is instantiated, and a function name such as sum appears inside it, the compiler finds all overloads of sum that have been declared so far. Thus, according to your theory, since the sum function template is not instantiated until it is called in main, at that point, both overloads of sum are visible, so the recursive calls to sum should consider both overloads and eventually select the unary one to terminate the recursion.
However, as you've seen, that's not the case. If the variadic sum is declared first, it eventually recursively calls itself with a single argument (ignoring the unary sum overload declared later), which then attempts to call sum() (no arguments), leading to a compilation error.
In this example, it thus appears that when the compiler sees a call to sum inside a function template, it only finds functions named sum that have been declared at the point of the call. When you switched the order around, you made it so that the variadic sum could never call the unary sum.
Actually though, the truth is more complicated. The C++ standard requires a behaviour that is colloquially referred to as "two-phase lookup". What this means is:
when the compiler sees the definition of the function template, it finds all functions named sum that have been declared so far, and
when the compiler later instantiates the function template, it uses argument-dependent lookup to find additional overloads of sum regardless of whether they were declared before or after the enclosing template.
In your code, sum is only ever called with arguments of type int, which does not belong to any namespace. Thus, the variadic sum only finds itself in phase 1, and nothing in phase 2.
|
73,314,521
| 73,314,605
|
c++ child copy constructor not saving member variable
|
I want to create copy constructor only for the derived class as so:
template <typename T>
class base_list {
public:
base_list() noexcept = default;
base_list(std::initializer_list<T> il)
: list_{il} {}
friend auto operator<<(std::ostream& os, base_list const& sl) -> std::ostream& {
if (sl.list_.size() == 0) {
return os;
}
for (auto const& element : sl.list_) {
os << '|' << element;
}
os << '|';
return os;
}
auto get_list() const -> std::list<T> {
return list_;
}
private:
std::list<T> list_;
};
template <typename T>
class derived_list : public base_list<T> {
public:
derived_list(std::initializer_list<T> il) : base_list<T>(il) {};
explicit derived_list(base_list<T> const& other) {
list_ = other.get_list();
for (auto const& element : list_) {
std::cout << "ELEMENT: " << element << '\n';
}
}
private:
std::list<T> list_;
};
I'm testing it using the below code.
auto bl = q2::base_list<double>{ 1.0, 1.5, 2.0 };
auto dl = q2::derived_list<double>(bl);
auto out = std::ostringstream{};
out << dl;
auto const expected_output = std::string{"|1|1.5|2|"};
CHECK(out.str() == expected_output);
Can see the elements showing up in the loop but the test fails showing the list is empty... Why isn't the data being saved in list_? Thanks
ELEMENT: 1
ELEMENT: 1.5
ELEMENT: 2
....
FAILED:
CHECK( out.str() == expected_output )
with expansion:
"" == "|1|1.5|2|"
|
What's happening here is somewhat analogous to an old-fashioned game of musical chairs.
You have a
std::list<T> list_;
that's declared as a private member of the base_list. And as an extra bonus you also have a
std::list<T> list_;
that's declared as a private member of the derived_list. They happen to have the same name but they have absolutely nothing to do with each other, whatsoever. This would be exactly the same as declaring a std::list<T> a; in one, and std::list<T> b; in the other. Just because they have the same name doesn't mean they're the same object, they're not, C++ does not work this way. Each class is fully responsible for its class members, and whatever happens in some other class it's derived from, or which derives from it, does not affect it's own class members. They're two different classes. And you've got two different list_ objects here, each one a private member of its class.
So confusion galore, with two members of classes, with the same name. So, the end result is a game of musical chairs: where will the list of values actually end up?
auto bl = q2::base_list<double>{ 1.0, 1.5, 2.0 };
This constructs a base_list, and the values end up in base_list's list_.
auto dl = q2::derived_list<double>(bl);
This constructs a derived_list, and this copies from list_ in the base_list to the list_ in the derived_list. The game of musical chairs has begun. Currently:
base_list::list_ is empty.
derived_list::list_ contains the values.
out << dl;
This calls the operator<< overload in the base_list, which dutifully shows its own, empty, list_ as the conclusion to this game of musical chairs.
The constructor is, actually, "saving member variable". The problem is that the << overload is looking at a completely different variable that has nothing to do, whatsoever, with the other variable.
|
73,315,164
| 73,317,526
|
How to use Objective-C sources' ExplicitInit class?
|
In the Objc source code, I found the following code. What is the meaning of this code and how to understand it?
objc/Project Headers/DenseMapExtras.h line:38
template <typename Type>
class ExplicitInit {
alignas(Type) uint8_t _storage[sizeof(Type)];
public:
template <typename... Ts>
void init(Ts &&... Args) {
new (_storage) Type(std::forward<Ts>(Args)...);
}
Type &get() {
return *reinterpret_cast<Type *>(_storage);
}
};
Below is my test code:
class MyC{
public:
long l1;
long l2;
MyC(long _l1, long _l2){
l1 = _l1;
l2 = _l2;
}
};
int main(){
MyExplicitInit<MyC> e1 {};
e1.init();
return 0;
}
The compiler prompts the following error:
|
In the Objc source code, I found the following code. What is the
meaning of this code and how to understand it?
To me it looks like a kind-of-factory which can be used as an alternative to the Construct On First Use Idiom. An instantiated class here represents a storage for an instance you can initialise and request when needed. As far as I understand it's not supposed to be used for local variables (it doesn't make much sense, despite being technically possible) and this is also suggested by the comments of code section with the said class template:
// We cannot use a C++ static initializer to initialize certain globals because
// libc calls us before our C++ initializers run. We also don't want a global
// pointer to some globals because of the extra indirection.
//
// ExplicitInit / LazyInit wrap doing it the hard way
For the error you are experiencing:
No matching operator new function for non-allocating placement new expression;
include <new>
Assuming that you just added that piece of code somewhere in your own sources, the problem here is that you didn't include the <new> header. As simple as that - the error just says that you need to add #include <new> since so-called placement new is not part of the "default" C++, it's an overloaded operator declared in this header.
Second, your init function expects arguments that matches one of the existing (non-aggregate) constructors of the given class, so you are expected to pass arguments which are either match the constructor parameters or can be implicitly converted to them: e1.init(1l, 2l)
A complete example looks something like this:
#include <_types/_uint8_t.h>
#include <new>
namespace objc {
template <typename Type>
class ExplicitInit {
alignas(Type) uint8_t _storage[sizeof(Type)];
public:
template <typename... Ts>
void init(Ts &&... Args) {
new (_storage) Type(std::forward<Ts>(Args)...);
}
Type &get() {
return *reinterpret_cast<Type *>(_storage);
}
};
};
struct sample_struct {
long l1, l2;
sample_struct(long _l1, long _l2): l1{_l1}, l2{_l2} {}
};
sample_struct& getInstance(bool should_init = false) {
static objc::ExplicitInit<sample_struct> factory;
if (should_init) {
factory.init(1l, 2l);
}
return factory.get();
}
|
73,315,541
| 73,315,586
|
What is wrong with my code? I get an error saying I have no declared 'name' but I do not know how to do this (beginner)?
|
For this program I am trying to make first ask for the users name, print this as a lowercase, and then make a menu, and then for option 1 the program asks the user to guess a random number between 1-100. When I try to run the below code, the error I get is:
program.cpp:51:11: error: 'name' was not declared in this scope; did you mean 'tzname'?
51 | cin>>name;
| ^~~~
| tzname
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "splashkit.h"
#include <string>
using namespace std;
void play_game()
{
int random = rand() % 101; //has to be 101 as when it divides it will be between 1-100
std::cout << random << std::endl;
std::cout << "Guess a number: ";
while(true)
{
int guess;
std::cin >> guess;
if(guess == random)
{
std::cout << "You win!\n";
break; //stops program if guessed right, otherwise keep going
}
else if (guess < random)
{
std::cout << "Too low\n";
}
else if (guess > random)
{
std::cout << "Too high\n";
}
}
}
void toSmall(char * name) //function to convert characters to lower case
{
int i=0;
while(name[i]!= '\0'){
if(name[i]>=65 && name[i]<=90){
name[i]= name[i]+ 32;
}
i++;
}
}
int main()
{
srand(time(NULL)); //to stop same sequence appearing everytime, seeds a random number each
time
cout<<"\nEnter your name: ";
cin>>name;
toSmall(name) ; //converts all character to lowercase
cout<<"Welcome To the Game: \n"<<name;
int choice;
do
{
std::cout << "0. Quit" << std::endl << "1. Play Game\n";
std::cin >> choice;
switch(choice)
{
case 0:
std::cout << "Game quit\n";
return 0;
case 1:
play_game();
break;
}
}
while(choice != 0);
}
|
What is wrong with my code? I get an error saying I have no declared 'name'
The problem is that there is no variable named name inside main(). That is, you're trying to read into name using cin>>name; when there is no variable called name that can be used here.
To solve this you can create a variable called name of type say std::string before trying to read into it:
std::string name;
std::cin >> name;
Note also that you can then pass name to toSmall by changing its declaration to
//-----------------------v------->pass by reference
void toSmall(std::string &pname)
{
//code here
}
You can also use std::to_lower if you're allowed to use library function instead of writing one yourself.
|
73,315,667
| 73,315,936
|
How to implement a std::function with operator= that can check if its rhs has same signature
|
I'm learning to implement std::function and have found several articles about this. Unfortunately, none of their implementations can report a mistake when I assign a funtor with different signature. However, the STL version can alert me as I expect. Obviously, this kind of feature is useful to check such stupid mistake beforehand.
I read the source of MSVC implementation, but can not understand what happened within the template argument _Enable_If_callable_t of function& operator=(_Fx&& _Func) of std::function. Seems like this SFINAE trick prohibits such wrong assignment operator existing.
Please tell me the theory behind this and if I can implement such feature in my handmaking version.
|
Cppreference says about operator=:
Sets the target of *this to the callable f, as if by executing function(std::forward(f)).swap(*this);. This operator does not participate in overload resolution unless f is Callable for argument types Args... and return type R.
This can be easily checked with std::is_invocable_r helper:
#include <type_traits>
template <class>
class function {};
template <class R, class... Args>
class function<R(Args...)> {
public:
template <typename F, typename x = std::enable_if_t<
std::is_invocable_r<R, F, Args...>::value>>
function& operator=(F&& f) {
// logic...
return *this;
}
};
#include <functional>
#include <string>
void bar1(std::string) {}
void bar2(int) {}
void bar3(float) {}
int bar4(int) { return 0; }
int main(int argc, char** argv) {
//std::function<void(int)> f;
function<void(int)> f;
// f = bar1; ERROR
f = bar2;
f = bar3;
f = bar4;
return 0;
}
I am using the SFINAE version with an extra template argument as I find it most clear but return-value-based can be used too.
Same as for std::function, this is really forgiving - extra return values in case of R=void are ignored, implicit conversions are enabled. This matches what std::is_invocable_r allows.
|
73,315,831
| 73,315,923
|
Is post-incrementing the iterator during a container erase always a bug?
|
Debugging some code, I found an invalid use of an iterator. So I searched our code-base for further bad usages. I found a few of these:
it = cppContainer.erase( it++ );
(Where it is a valid container iterator before this line, and cppContainer is a STL container, e.g. vector).
This sparked a discussion on whether the it++ was merely redundant, or whether it was post-incrementing the iterator after the call to the container .erase() made it invalid, which would be bad.
Is this form always a bug? Obviously the ++ is unnecessary, but is it wrong?
The general consensus among the engineers was that it was potentially bad.
|
or whether it was post-incrementing the iterator after the call to the container .erase() made it invalid.
Please note that the arguments are fully evaluated before the function is called. You can conceptually imagine the post-increment as below:
auto operator++(int) {
auto cp = *this;
++*this;
return cp;
}
As you can see, the increment is done before the erase function is called; ergo, this is not undefined, but possibly inefficient.
The only way this would be undefined is if it++ is already undefined on its own. For instance, it is the end iterator, or it is already invalidated, etc.
|
73,315,971
| 73,316,118
|
Declare C++ Class (identifier logging is undefined)
|
I'm a complete newbie to C++ so bear with me. I am defining a class called 'logging' which is currently write in main.cpp. Now that I am trying to split implementation (log.cpp) from declaration (log.h), I have the following situation that bring me to compiler error 'identifier logging is undefined':
log.cpp
#include <iostream>
#include <unordered_map>
#include <string>
#include "..\h\log.h"
class logging {
public:
std::unordered_map<int, std::string> m_log_levels;
logging() {
m_log_levels[2] = "info";
m_log_levels[1] = "warning";
m_log_levels[0] = "error";
}
private:
int m_level = 2;
public:
void setLevel(int level) {
m_level = level;
}
void log(const char* message) {
std::string sm = "[" + m_log_levels.at(m_level) + "]: ";
std::cout << sm + message << std::endl;
}
};
log.h
#pragma once
#include <unordered_map>
#include <string>
class logging {
public:
std::unordered_map<int, std::string> m_log_levels;
private:
int m_level;
public:
void setLevel(int level);
void log(const char* message);
};
main.cpp
#include <iostream>
#include "..\h\log.h"
int main() {
logging logger; /* -> identifier logging is undefined */
}
Build started...
1>------ Build started: Project: learn, Configuration: Debug x64 ------
1>log.cpp 1>main.cpp
1>C:\Users\pietr\source\repos\learn\learn\src\main.cpp(8,2): error C2065: 'logging': undeclared identifier
1>C:\repos\learn\learn\src\main.cpp(8,10): error C2146: syntax error: missing ';' before identifier 'logger'
1>C:\repos\learn\learn\src\main.cpp(8,10): error C2065: 'logger': undeclared identifier 1>Generating Code...
1>Done building project "learn.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
|
The main problem is that you're defining the class logging twice. Instead you should put the class definition with only the declaration of the members functions in the header and then implement the member functions in the source file as shown below:
log.h
#pragma once
#include <unordered_map>
#include <string>
class logging {
public:
std::unordered_map<int, std::string> m_log_levels;
private:
int m_level;
public:
logging(); //declaration for default constructor
void setLevel(int level); //this is declaration
void log(const char* message); //this is declaration
};
log.cpp
#include <iostream>
#include <unordered_map>
#include <string>
#include "log.h"
//definition of default ctor using member initializer list
logging::logging() :m_log_levels{{0, "error"},{1, "warning"}, {2,"info"}}, m_level(2){
}
//this is definition of member function
void logging::setLevel(int level) {
m_level = level;
}
//this is definition of member function
void logging::log(const char* message) {
std::string sm = "[" + m_log_levels.at(m_level) + "]: ";
std::cout << sm + message << std::endl;
}
main.cpp
#include "log.h"
int main()
{
logging log;
return 0;
}
Working demo
|
73,316,465
| 73,316,683
|
How to use win api to check if the network is a pay-per-traffic link
|
I see that since windows8 users can set up network as a pay-per-traffic internet link, so maybe some apps will use less data traffic
But I can't find an easy to use api to determine if the current network is billed or not when developing c++ applications
Does anyone have a link to the documentation for this?
|
Windows::Networking::Connectivity::NetworkInformation class is what you seek.
The GetInternetConnetionProfile method on this class returns a ConnectionProfile instance. On that object, you can invoke GetConnectionCost to get the NetworkCostType enum property. There's an event you can register a callback for when the user roams between networks so you know when to query it again.
If this property is "fixed" or "variable", you're on some sort of "metered network" connection where you might not want to have your app be conservative on network usage.
With that in mind, I believe the property that sets this bit simply a property of the network adapter. And maps to the user setting buried in Windows Settings:
I could be mistaken, but I'm not sure if there's any well known standard by which a network or ISP advertises the metered connection property dynamically in which Windows will pick it up. I think the OEM of the device sets this toggle switch when the machine is imaged.
|
73,316,922
| 73,317,031
|
how to understand void (*&&)() func
|
I use C++ https://cppinsights.io/ to see the progress of instantiation, and there's something puzzled between Function&& and Function.
I comment the code generated by cppinsights.
template<typename Function>
void bind(int type, Function&& func)
{
}
/*
// instantiated from the function above:
template<>
inline void bind<void (*)()>(int type, void (*&&)() func)
{
}
*/
template<typename Function>
void bindtwo(int type, Function func)
{
}
/*
template<>
inline void bindtwo<void (*)()>(int type, void (*func)())
{
}
*/
void test()
{
std::cout << "test" << std::endl;
}
int main()
{
bind(1, &test);
bindtwo(2, test);
}
|
how to understand void (*&&)() func
First things first, the above syntax is wrong because func should appear after the && and not after the () as shown below.
Now after the correction(shown below), func is an rvalue reference to a pointer to a function that takes no parameter and has the return type of void.
Note also that the syntax void (*&&)() func is wrong, the correct syntax would be as shown below:
template<>
//----------------------------------------------vvvv----->note the placement of func has been changed here
inline void bind<void (*)()>(int type, void (*&&func)() )
{
}
|
73,317,885
| 73,324,561
|
gcc - C++ error "declaration changes meaning" - error appears on linux gcc 11.3, but not on msys2 gcc 12.1. how to force it?
|
With this code:
enum class profession
{
doctor,
banker
};
class person
{
profession profession;
};
int main()
{
}
on linux (opensuse 15.4 with gcc 11.2), compilation command
g++ -std=c++20 -pedantic -Wall -Wextra -Werror=return-type -Wshadow=local -Wempty-body -fdiagnostics-color -s -Os -o program_gpp program.cpp
I get the error :
error: declaration of ‘profession person::profession’ changes meaning of ‘profession’ [-fpermissive]
while on windows (windows 10 pro, 21h1) / msys2 / mingw-w64 / gcc 12.1, compilation command:
g++ -std=c++20 -pedantic -Wall -Wextra -Werror=return-type -Wshadow=local -Wempty-body -fdiagnostics-color -s -Os program.cpp -o program_gpp.exe
I don't get any warning or error, nothing.
I had already found somewhere that maybe gcc itself is built with different switches for the two platforms, and so its sensibility to some errors changes among them, and this is ok. But since I would like my code to avoid this error and compile everywhere, which gcc switches can I use to force this error also on the gcc on windows / msys2 ? note : I don't want to disable the error on linux (the compiler already tells me that it can be disabled with -fpermissive), I want gcc on windows to give me the error too so that I can fix it there and it will also compile on linux.
|
Pass -fno-ms-extensions to MSYS2 GCC. This disables some MSVC-esque extensions.
|
73,318,411
| 73,318,604
|
C++ transform std::pair<std::pair<std::pair<A, B>, C>, D> to std::tuple<A, B, C, D>
|
I have such kind of code:
const auto temp = std::make_pair(std::make_pair(std::make_pair('Q', 1.2),
std::string("POWER")), 1);
std::cout << std::format("({}, {}, {}, {})\n", temp.first.first.first,
temp.first.first.second, temp.first.second, temp.second);
that obviously prints:
(Q, 1.2, POWER, 1)
I want to make it more readable and intuitive by converting "pair of pair and smth" to std::tuple:
const auto temp = std::make_pair(std::make_pair(std::make_pair('Q', 1.2),
std::string("POWER")), 1);
const auto tuple = PairsToTuple(temp);
std::cout << std::format("({}, {}, {}, {})\n", std::get<0>(tuple),
std::get<1>(tuple), std::get<2>(tuple), std::get<3>(tuple));
How can I do that?
|
You can recursively std::tuple_cat
template<typename First, typename Second>
auto flatten(std::pair<First, Second> pair) {
return std::tuple_cat(flatten(pair.first), flatten(pair.second));
}
template<typename... Types>
auto flatten(std::tuple<Types...> tup) {
return std::apply([](auto... args) { return std::tuple_cat(flatten(args)...);}, tup);
}
template<typename T>
auto flatten(T t) {
return std::tuple{ t };
}
See it on coliru
If you have C++20, we can generalise this to anything tuple-like with a concept:
template<typename T>
auto flatten(T&& t) {
if constexpr (tuple<std::remove_cvref_t<T>>) {
return [&]<std::size_t... Is>(std::index_sequence<Is...>) {
return std::tuple_cat(flatten(get<Is>(std::forward<T>(t)))...);
}(std::make_index_sequence<std::tuple_size_v<std::remove_cvref_t<T>>>{});
} else {
return std::tuple{ std::forward<T>(t) };
}
}
See it on coliru
|
73,318,618
| 73,318,705
|
Qt: Displaying an int in a message box
|
I have a timer/clock that displays a message X amounts of seconds (usually 10) after it has been clicked. I attempted to set up an int that one could set easily to change what X is, however I am having trouble with displaying the message, which includes the value of X, in a message box.
What I want:
Where the value "10" is changed by an int.
The specific line of code for the messagebox:
void MainWindow::messageBox(){
QMessageBox::information(this, "Warning!", "You clicked the button of doom " + timerLength/1000 + " seconds ago!");
} //timerLength is an int.
mainwindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <qDebug>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
QTimer *timer = new QTimer(this); //Set up timer.
connect(timer, SIGNAL(timeout()), this, SLOT(showtime()));
//showtime();
timer->start();
messageBox();
otherTimer = new QTimer(this);
otherTimer->setSingleShot(true);
connect(otherTimer, SIGNAL(timeout()), this, SLOT(messageBox()));
}
void MainWindow::showtime(){ //Displays current time. Needs to be manually updated.
QTime time = QTime::currentTime();
QString lcdText = time.toString("mm:ss");
ui->lcdNumber->QLCDNumber::display(lcdText);
}
MainWindow::~MainWindow(){
delete ui;
}
void MainWindow::on_pushButton_clicked(){
int timerLength = 10000;
otherTimer->start(timerLength);
QPropertyAnimation *progresBar = new QPropertyAnimation(ui->graphicsView, "geometry");
progresBar->setDuration(timerLength);
QRect barLocation =ui->graphicsView->geometry();
progresBar->setStartValue(QRect(barLocation.x(), barLocation.y(), 0, barLocation.height()));
progresBar->setEndValue(barLocation);
progresBar->start();
}
void MainWindow::messageBox(){
QMessageBox::information(this, "Warning!", "You clicked the button of doom " + timerLength/1000 + " seconds ago!");
}
main.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QTimer>
#include <QDateTime>
#include <QLCDNumber>
#include <QMessageBox>
#include <QPropertyAnimation>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
int timerLength;
public slots:
void showtime();
void messageBox();
private slots:
void on_pushButton_clicked();
private:
Ui::MainWindow *ui;
QTimer *otherTimer;
};
#endif // MAINWINDOW_H
Please let me know if more information or explanation is required.
|
You can convert your number to QString like
void MainWindow::messageBox(){
QMessageBox::information(this, "Warning!", "You clicked the button of doom " + QString::number(timerLength/1000) + " seconds ago!");
} //timerLength is an int.
I tried it works in my app.
|
73,318,680
| 73,318,911
|
Can the space complexity of a solution using recursive function be O(1)?
|
I have solved the 98th problem in leetcode
and this is my solution:
class Solution {
public:
long long pre;
bool check(TreeNode *node) {
if(!node) return true;
bool left = check(node->left);
bool mid = node->val > pre;
pre = node->val;
bool right = check(node->right);
return left & mid & right;
}
bool isValidBST(TreeNode* root) {
pre = (long long)INT_MIN - 1;
return check(root);
}
};
However, I am not sure if this solution consumes O(n) or O(1) space since someone told me that a recursive function would make use of stack, which makes this solution consume O(n) space.
But in my opinion, pre is not an parameter of a recursive function. Besides, pre's original value won't be needed anymore whenever it is changed since check(node) traverse a tree in in-order and whenever a node's value has been compared with pre, it won't be visited in the future, so it only consume O(1) space.
Please help me to clarify the problem.
|
You need O(max tree depth) space for the parameters and local variables. For a balanced tree, that's O(log nodes), and for a maximally imbalanced tree, that's O(nodes).
The stack frame for the call to check(parent) has to exist at the same time as the stack frame for it's call check(parent->left) (and similarly check(parent->right)). What you don't need is the stack frame of check(parent->left) to exist at the same time as that of check(parent->right).
|
73,318,732
| 73,341,847
|
Qt6 - Draw custom metatype in table/tree from QAbstractTableModel
|
If I have an overridden QAbstractTableModel that supplies a non-qt type, it's my understanding that supplying overloads for the << and >> operators will allow Qt to natively represent those types.
I have prepared an example with std::u16string in an attempt to create the most minimal test case, but can't seem to render anything.
Here's how I register the type with Qt:
#include <QtCore>
Q_DECLARE_METATYPE(std::u16string);
QDataStream& operator<<(QDataStream& out, const std::u16string& myObj)
{
return out << QString::fromStdU16String(myObj);
}
QDataStream& operator>>(QDataStream& in, std::u16string& myObj)
{
QString tmp;
in >> tmp;
myObj = tmp.toStdU16String();
return in;
}
My trivial main.cpp which connects the type to the appropriate widget:
#include <QItemEditorFactory>
#include <QLineEdit>
int main()
{
// not sure if this is required.
// this blogpost (https://www.qt.io/blog/whats-new-in-qmetatype-qvariant) suggests it's
// needed for name-to-type conversions, but no idea if that is still needed internally.
qRegisterMetaType<std::u16string>();
// tell qt that we would like to visualise std::u16string with the default text editor.
QItemEditorFactory* factory = new QItemEditorFactory;
factory->registerEditor(QMetaType::fromType<std::u16string>().id(), new QStandardItemEditorCreator<QLineEdit>());
QItemEditorFactory::setDefaultFactory(factory);
// kick off ui, etc
return doApp();
}
And my trivial model, which supplies the external type via a variant:
#include <QAbstractTableModel>
class simple_model : public QAbstractTableModel
{
public:
explicit simple_model(QObject* parent = nullptr) : QAbstractTableModel(parent) {}
QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override
{
return QVariant::fromValue<std::u16string>(u"Hello, World!");
}
};
Now, when I create QTableView like so:
QTableView* tableView = new QTableView;
tableView->setModel(new simple_model);
I would expect every column and row to print "Hello, World!". However, I just get a blank text box instead. Attaching my debugger to my overloaded << and >> operators shows they don't get run at all.
I feel like I'm missing a link here, but I'm not quite sure what. Some ideas about what could possibly be wrong:
Do I need to create a custom delegate and set it for each row and column which I'm returning this value? Ideally, I'd like my types to be interpreted as automatically and naturally as Qt would allow; I feel like it could create a lot of boilerplate code in my (actual, non-trivial) application.
Does QLineEdit not actually invoke any data conversions to display custom data? Perhaps there's a more appropriate text editor I should be using? I was hoping that QLineEdit would automatically convert them because it's the default QString editor; would be nice to have the exact same behaviour.
|
In my case, it turns out that the << and >> operators weren't needed at all. Instead, providing an appropriate meta type converter allowed for what I wanted.
Sample code for converter:
struct string_converter
{
static QString toQString(const std::u16string& value)
{
return QString::fromStdU16String(value);
}
static std::u16string tou16String(const QString& value)
{
return value.toStdU16String();
}
};
and to register these converters:
QMetaType::registerConverter<std::u16string, QString>(&string_converter::toQString);
QMetaType::registerConverter<QString, std::u16string>(&string_converter::tou16String);
Once these are provided, no other registration code appears to be needed. The simple_model seems to be able to construct a QVariant from the std::u16string and represent it with a QLineEdit without any extra boilerplate code.
However, we'll need to explicitly convert the modified data back to std::u16string in simple_model, because they get tweaked and returned as a QString from QLineEdit. Eg:
QVariant simple_model::setData(const QModelIndex& index, const QVariant& value, int role) override
{
std::u16string newData = value.value<std::u16string>();
// do something with newData
}
While this has unblocked me, I'm not sure this is preferred Qt approach as it seems to be quite different to what the documentation says (as I cited originally in the question). Any extra feedback or tips would be appreciated.
|
73,318,893
| 73,319,532
|
Application fails to launch via Visual Studio 2003 - CURLE_NOT_BUILT_IN Curl error displayed in debugger
|
We have a legacy MFC based application in our company which is built with Visual C++98 on Visual Studio 2003. We use curl for Http requests. libcurl.lib file is linked into the project.
I see 2 behaviors while executing the HTTP requests.
When we launch the application from Visual studio or the bin folder directly, I get an CURLE_NOT_BUILT_IN error and the application refuses to proceed further.
When the application is packaged and installed in another folder via an installer, the application runs perfectly fine. 0 issues whatsoever.
Can anyone help me understand why the application fails to launch via the Visual studio?
Note: libcurl.lib file has been in the repository since ages. Also, this issue propped up recently. It was working fine 2 weeks ago and affects only my computer.
|
I figured out what the issue was.
libcurl.dll was missing the bin/rel folder and hence CURL was throwing the error CURLE_NOT_BUILT_IN. I have manually copied the file to that folder and the application is working well
|
73,319,796
| 73,322,243
|
Why would you declare a std::string using it's constructor?
|
Most people when declaring strings in C++, or most other languages, do it like so:
std::string example = "example";
However I've seen some code samples where it is done like this:
std::string example("example");
To me it seems like it needlessly obfuscates the code, particularly if there is a using std::string statement hiding somewhere above the declaration in the code making it look like
string example("example");
To some who may be new to the codebase or are coming from other languages it almost looks like it could be a method or a function.
Is there any practical or performance based reason for using the constructor instead of the assignment operator or does it come down to just personal preference?
|
The practical reason for the second form is that it reflects what actually happens. Your two examples actually - despite their syntactic differences - do exactly the same thing.
They are both calling a constructor which accepts a const char * to initialise example with the literal "example".
The main difference is the way they are interpreted at times. I've lost count of the number of times I've seen people insist that
std::string example = "example";
does an assignment that calls std::strings operator=() function - except that it doesn't.
People who get tired of fielding such claims (and prefer that someone looking at the code can understand what it actually does, wherever possible) therefore sometimes prefer the second form;
std::string example("example");
|
73,319,953
| 73,321,989
|
What is the difference between lambda capture [&args...] and [...args = std::forward<Args>(args)]
|
I'm writing a simple game with Entity Component System. One of my components is NativeScriptComponent. It contains the instance of my script. The idea is that I can create my NativeScriptComponent anytime and then Bind to it any class implementing Scriptable interface. After that my game's OnUpdate function will automatically instantiate all scripts in my game and will call their OnUpdate function.
My scripts can have their own, different constructors so I need to forward all the arguments to them when I bind my script.
Consider the following code:
#include <iostream>
#include <memory>
#include <functional>
using namespace std;
struct Scriptable
{
virtual void OnUpdate() {};
};
struct MyScript : Scriptable
{
MyScript(int n) : value(n) {}
void OnUpdate() override {cout << value;}
int value;
};
struct NativeScriptComponent
{
unique_ptr<Scriptable> Instance;
function<unique_ptr<Scriptable>()> Instantiate;
template<typename T, typename ... Args>
void Bind(Args&&... args)
{
// (A)
Instantiate = [&args...]() { return make_unique<T>(forward<Args>(args)...); };
// (B) since C++20
Instantiate = [...args = forward<Args>(args)]() { return make_unique<T>(args...); };
}
};
int main()
{
NativeScriptComponent nsc;
nsc.Bind<MyScript>(5);
// [..] Later in my game's OnUpdate function:
if (!nsc.Instance)
nsc.Instance = nsc.Instantiate();
nsc.Instance->OnUpdate(); // prints: 5
return 0;
}
1) What is the difference between option A and B
Instantiate = [&args...]() { return make_unique<T>(forward<Args>(args)...); };
vs
Instantiate = [...args = forward<Args>(args)]() { return make_unique<T>(args...); };
Why can't I use forward<Args>(args) inside make_unique in option B?
Are both A and B perfectly-forwarded?
|
For added completeness, there's more things you can do. As pointed out in the other answer:
[&args...]() { return make_unique<T>(forward<Args>(args)...); };
This captures all the arguments by reference, which could lead to dangling. But those references are properly forwarded in the body.
[...args=forward<Args>(args)]() { return make_unique<T>(args...); };
This forwards all the arguments into the lambda, args internally is a pack of values, not references. This passes them all as lvalues into make_unique.
[...args=forward<Args>(args)]() mutable { return make_unique<T>(move(args)...); };
Given that, as above, args is a pack of values and we're creating a unique_ptr anyway, we probably should std::move them into make_unique. Note that the lambda has its own internal args here, so moving them does not affect any of the lvalues that were passed into this function.
[args=tuple<Args...>(forward<Args>(args)...)]() mutable {
return std::apply([](Args&&... args){
return std::make_unique<T>(forward<Args>(args)...);
}, std::move(args));
};
The most fun option. Before we'd either capture all the arguments by reference, or forward all the args (copying the lvalues and moving the rvalues). But there's a third option: we could capture the lvalues by reference and move the rvalues. We can do that by explicitly capturing a tuple and forwarding into it (note that for lvalues, the template parameter is T& and for rvalues it's T - so we get rvalues by value).
Once we have the tuple, we apply on it internally - which gives us Args&&... back (note the && and that this is not a generic lambda, doesn't need to be).
This is an improvement over the previous version in that we don't need to copy lvalues -- or perhaps it's worse because now we have more opportunity for dangling.
A comparison of the four solutions:
option
can dangle?
lvalue
rvalue
&args...
both lvalues and rvalues
1 copy
1 move
...args=FWD(args) and args...
no
2 copies
1 move, 1 copy
...args=FWD(args) and move(args)...
no
1 copy, 1 move
2 moves
args=tuple<Args...>
lvalues
1 copy
2 moves
|
73,320,722
| 73,334,755
|
Function that takes VectorXf and can modify its values
|
I am trying to understand how to manipulate Eigen Vector/Matrix. I would like to implement a least-square gauss-newton algorithm (hence why I am learning to use the Eigen library). I have a 1x6 vectors of parameters that I need to update each iteration. Right now, I just want to figure out how a function can take a vector as argument and change its values...
Eigen::VectorXf betas = Eigen::VectorXf::Zero(6);
void SomeFunc(const Eigen::VectorXf& v){ // as per the Eigen guide, one must pass as const
v(0) = 5; // error: expression must be a modifiable lvalue
return;
}
int main()
{
betas(5) = 5.f; // works
SomeFunc(&betas);
std::cout << "Hello World" << std::endl;
std::cout << betas(0) << "\t" << betas(5) << std::endl;
}
My question is: How would you make a function take a vector and modify its values?
Edit: Eigen guide
|
I believe the purpose of that section of the documentation is to make you aware of the potential pitfalls that come from the various temporary objects that Eigen creates as it goes through various operations. You can write functions that take writable references such as foo(Eigen::VectorXf &vector) and it will work. One problem that can occur with this is if you pass a slice of a matrix into the function thinking it is vector linked back the parent matrix. What you actually pass into the function is a temporary vector that will be destroyed. If you are 100% certain of what you are passing you can use references directly. Otherwise there are safer things to do as suggested by the documentation. Here are 3 versions of the same function.
You can see this stackoverflow question for a discussion of the correct usage of the Eigen::Ref class.
#include <iostream>
#include <Eigen/Dense>
void SomeFunc(Eigen::Ref<Eigen::VectorXf> v);
void SomeFunc2(Eigen::VectorXf &v);
void SomeFunc3(const Eigen::VectorXf &v);
int main(int argc, char * argv[]) {
Eigen::VectorXf betas = Eigen::VectorXf::Zero(6);
std::cout << "Original\n";
std::cout << betas << '\n';
SomeFunc(betas);
std::cout << "SomeFunc\n";
std::cout << betas << '\n';
betas.setZero();
SomeFunc2(betas);
std::cout << "SomeFunc2\n";
std::cout << betas << '\n';
betas.setZero();
SomeFunc3(betas);
std::cout << "SomeFunc3\n";
std::cout << betas << '\n';
return 0;
}
void SomeFunc(Eigen::Ref<Eigen::VectorXf> v) {
v(0) = 5;
}
void SomeFunc2(Eigen::VectorXf &v) {
v(2) = 5;
}
void SomeFunc3(const Eigen::VectorXf &v) {
const_cast<Eigen::VectorXf&>(v)(4) = 5;
}
To quote from the linked question above:
So in summary, we could recommend Ref for a writable reference, and const Ref& for a const reference.
|
73,320,886
| 73,331,280
|
How to link a C++11 program to the Adept library
|
Adept (http://www.met.reading.ac.uk/clouds/adept/) is a C++ library for automatic differentiation. The following example, placed in a file called home_page.cpp is taken from the home page for the library:
#include <iostream>
#include <adept_arrays.h>
int main(int argc, const char** argv)
{
using namespace adept;
Stack stack;
aVector x(3);
x << 1.0, 2.0, 3.0;
stack.new_recording();
aReal J = cbrt(sum(abs(x*x*x)));
J.set_gradient(1.0);
stack.reverse();
std::cout << "dJ/dx = "
<< x.get_gradient() << "\n";
return 0;
}
I can compile this on my Mac using g++ -Wall -O2 home_page.cpp -ladept -llapack -lblas -o home_page.
However, if I try to compile using the C++11 standard, using g++ -Wall -O2 -std=c++11 home_page.cpp -ladept -llapack -lblas -o home_page, I get a long error message:
Undefined symbols for architecture x86_64:
"thread-local wrapper routine for adept::_stack_current_thread", referenced from:
_main in home_page-758c45.o
adept::internal::Allocator<1, adept::Array<1, double, true> > adept::operator<<<1, double, true, double>(adept::Array<1, double, true>&, double const&) in home_page-758c45.o
adept::Active<double>::~Active() in home_page-758c45.o
adept::Array<1, double, true>::resize(int const*, bool) in home_page-758c45.o
adept::Storage<double>::remove_link() in home_page-758c45.o
void adept::internal::reduce_active<adept::internal::Sum<double>, double, adept::internal::UnaryOperation<double, adept::internal::Abs, adept::internal::BinaryOperation<double, adept::internal::BinaryOperation<double, adept::Array<1, double, true>, adept::internal::Multiply, adept::Array<1, double, true> >, adept::internal::Multiply, adept::Array<1, double, true> > > >(adept::Expression<double, adept::internal::UnaryOperation<double, adept::internal::Abs, adept::internal::BinaryOperation<double, adept::internal::BinaryOperation<double, adept::Array<1, double, true>, adept::internal::Multiply, adept::Array<1, double, true> >, adept::internal::Multiply, adept::Array<1, double, true> > > > const&, adept::Active<double>&) in home_page-758c45.o
adept::Active<double>::Active<double, adept::internal::UnaryOperation<double, adept::internal::Cbrt, adept::Active<double> > >(adept::Expression<double, adept::internal::UnaryOperation<double, adept::internal::Cbrt, adept::Active<double> > > const&, adept::internal::enable_if<((adept::internal::UnaryOperation<double, adept::internal::Cbrt, adept::Active<double> >::rank) == (0)) && (adept::internal::UnaryOperation<double, adept::internal::Cbrt, adept::Active<double> >::is_active), void>::type*) in home_page-758c45.o
...
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
How can I link a program to Adept when using the C++11 standard?
Thanks.
|
As has mentioned in the Adept library documentation, you should add this line to your main source file that includes the main() function:
#include <adept_source.h>
In addition, for every other source file of your code, you may include either adept.h or adept_arrays.h.
|
73,321,368
| 73,375,483
|
Camera2 byteArray to BGR uint8 mat conversion
|
I'm trying to convert byteArray from camera2 onImageAvailable listener to Mat object, and then passing it to an algorithm for dehazing in c++. I have tried different methods available for converting byteArray to Mat channel 3 object but whenever I split the mat object in 3 channels then all of them get filled with garbage data which further cause crash.
Here're the different methods used for converting byte array to mat
val bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
val orig = Mat(bmp.height, bmp.width, CvType.CV_8UC3)
val myBitmap32 = bmp.copy(Bitmap.Config.ARGB_8888, true)
Utils.bitmapToMat(myBitmap32,orig)
Using imread
val matImage = Imgcodecs.imread(file!!.absolutePath,IMREAD_COLOR)
using decodebyte array
val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
Utils.bitmapToMat(bitmap,matImage)
here's c code for the JNICALL
dehazing(JNIEnv *env, jobject, jlong input, jlong output)
{
cv::Mat& mInput = *((cv::Mat*) input);
cv::Mat& mOutput = *((cv::Mat*) output);
dehaze(mInput, mOutput);
}
and finally here's a little chunk of c++ code
Mat dehazedSplit[3];
Mat ABGR[3];
Mat tBGR[3];
Mat imageBGR[3];
Mat blurredImageBGR[3];
// Normalize, blur image and extract dimensions
W = image.cols;
H = image.rows;
image.convertTo(image, CV_64FC3);
image = image / Scalar(255, 255, 255);
GaussianBlur(image, blurredImage, Size(41, 41), 30, 30);
split(blurredImage, blurredImageBGR);
// Estimate the A matrix
A = Mat(H, W, CV_64FC3, Scalar(1, 1, 1));
split(A, ABGR);
minMaxLoc(blurredImageBGR[0], &minVal, &maxVal, &minLoc, &maxLoc);
ABGR[0] = Scalar(maxVal);
minMaxLoc(blurredImageBGR[1], &minVal, &maxVal, &minLoc, &maxLoc);
ABGR[1] = Scalar(maxVal);
minMaxLoc(blurredImageBGR[2], &minVal, &maxVal, &minLoc, &maxLoc);
ABGR[2] = Scalar(maxVal);
// Estimate the t matrix
t = Mat(H, W, CV_64FC3, Scalar(0, 0, 0));
split(t, tBGR);
tBGR[0] = (Scalar(1) - blurredImageBGR[0].mul(Scalar(twBlue)) / ABGR[0]);
tBGR[1] = (Scalar(1) - blurredImageBGR[1].mul(Scalar(twGreen)) / ABGR[1]);
tBGR[2] = (Scalar(1) - blurredImageBGR[2].mul(Scalar(twRed)) / ABGR[2]);
Any suggestion/help will be appreciated.
|
After a lot of discussion over OpenCV forum, the solution to convert ARGB to BRG came out as
Mat argb2bgr(const Mat &m) {
Mat _r(m.rows, m.cols, CV_8UC3);
mixChannels({m}, {_r}, {1,2, 2,1, 3,0}); // drop a, swap r,b
return _r;
}
The link to discussion is here
Besides it, what actually worked for me, was to drop the last channel of 4 channel MAT object this way
mixChannels({m}, {_r}, {0,0, 1,1, 2,2});
|
73,321,665
| 73,322,819
|
How to get real time std out from python script while using QProcess
|
here my code, real time output i can get only when using ping {address} in QLineEdit as cmd input. i want to same effect, but when execute python test.py.
QT C++ code:
#include "dialog.h"
#include "ui_dialog.h"
#include <QProcess>
QProcess proc;
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
, ui(new Ui::Dialog)
{
ui->setupUi(this);
connect(ui->btnStart, SIGNAL(clicked()), this, SLOT(startProcess()));
connect(ui->btnStop, SIGNAL(clicked()), this, SLOT(stopProcess()));
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::startProcess()
{
QString str1 = ui->textCmd->text(); // получаем строку из первого QLineEdit
connect(&proc, &QProcess::readyReadStandardOutput, this, &Dialog::slotDataOnStdout);
proc.start(str1);
}
void Dialog::stopProcess()
{
proc.close();
}
void Dialog::slotDataOnStdout()
{
QString output = proc.readAllStandardOutput().toStdString().c_str();
ui->outputCmd->append(output);
}
void Dialog::on_btnClean_clicked()
{
ui->outputCmd->clear();
}
Python test.py code
import time
while True:
print("test output")
time.sleep(1)
please help... maybe it's problem with executing python script? or with signal and slot connection in void Dialog::slotDataOnStdout()
ui image, if you really need this
app ui
|
fixed just by add -u flag for execute command.
example:
python3 -u test.py
problem was with buffering.
|
73,321,959
| 73,368,187
|
Why mciSendString cannot open my mp3 file?
|
I am trying to play MP3 audio in C++ Visual Studio 17.3.0, but keep getting MCIERROR 275 followed by 263.
My .mp3 file is in the same directory as my .cpp file.
My code goes something like this:
MCIERROR me = mciSendString(TEXT("open ""Music.mp3"" type mpegvideo alias mp3"), NULL, 0, NULL);
while(true){
me = mciSendString(TEXT("play mp3"), NULL, 0, NULL);
}
Have tried different .mp3 files, different directory, and different function for playing the sound (PlaySound()), which gave me a very similar result/error.
What could be the cause of my problem?
|
The first is to open:
mciSendString("open Summer.mp3 alias song",NULL,0,NULL)
Add the relative path or absolute path of the file after open (depending on the relative position of the music you play and your program)
We could understand alias as replacing your music name with the name after alias, which is convenient for us to carry out subsequent operations, only need to enter your alternative name (to save the trouble if the song name is long)
The last three parameters can be written as I do, because we are just simply playing music, so there is no need to go into details.
Next is to play:
mciSendString("play song repeat",NULL,0,NULL);
play+music name (or an alternative name after alias)+[play selection]
Playback options include repeat, wait.
repeat means to repeat the song.
wait means that the function does not return until the song has finished playing.
|
73,322,016
| 73,322,237
|
Overloading the output operator for a template class and a nested class
|
There is a template class in which a subclass is nested. How to properly overload the output operator to the stream for an external class, which is a template, in which the output operator to the stream is called from a nested class? In my case, compilation errors occur:
no type named 'type' in 'struct std::enable_if<false, void>'
no match for 'operator<<' (operand types are 'std::basic_ostream' and 'Nesting::Nested')
I give my code below.
#include <iostream>
#include <string>
using namespace std;
template<typename T>
class Nesting {
public:
class Nested {
public:
T data;
Nested(const T & data): data(data) {;}
template<typename U>
friend ostream & operator<<(ostream & out, const typename Nesting<U>::Nested & nested);
};
T data;
Nested * pNested;
Nesting(const T & data)
: data(data)
, pNested(new Nested(222)) {;}
template<typename U>
friend ostream & operator<<(ostream & out, const Nesting<U> & nesting);
};
template<typename T>
ostream & operator<<(ostream & out, const typename Nesting<T>::Nested & nested) {
out << "Nested: " << nested.data;
return out;
}
template<typename T>
ostream & operator<<(ostream & out, const Nesting<T> & nesting) {
out << "Nesting: " << nesting.data << ", " << *nesting.pNested << endl;
return out;
}
int main() {
Nesting<int> n(111);
cout << n << endl;
return 0;
}
|
I think the easiest thing to do is to provide the definition inline with the declaration.
#include <iostream>
#include <memory>
#include <string>
using std::cout;
using std::make_unique;
using std::ostream;
using std::unique_ptr;
template<typename T>
class Nesting {
public:
class Nested {
public:
T data;
Nested(T const& data_): data{data_} {}
friend auto operator<<(ostream& out, Nested const& nested) -> ostream& {
return out << "Nested: " << nested.data;
}
};
T data;
unique_ptr<Nested> pNested;
Nesting(T const& data_)
: data{data_}
, pNested{make_unique<Nested>(222)} {}
friend auto operator<<(ostream& out, Nesting const& nesting) -> ostream& {
return out << "Nesting: " << nesting.data << ", " << *nesting.pNested;
}
};
int main() {
Nesting<int> n(111);
cout << n << "\n";
}
|
73,322,114
| 73,323,599
|
Is it necessarily bad to use const_cast when working with legacy libraries?
|
I am writing a C++ program for Linux. I use many low-level libraries such as XLib, FontConfig, Xft etc. They are all written in pure C, and in some places in my code I have this annoying problem:
I wrap C structures in RAII-friendly classes, where resources are allocated in constructors and freed in destructors. Freeing most of these resources is not just calling free(), special library functions should be used instead (::XftFontClose(), ::FcPatternDestroy() etc), so I don't see benefits of using smart pointers. Instead, I keep read-only raw pointers to library resources inside my classes and provide getter functions returning constant pointers to these resources so that they are unable to be modified outside of the classes that own them.
For example, I have a class containing a sorted list of system fonts, and I can ask this class to find and open the best font that can be used to draw a specific character:
const ::XftFont* FontHandler::findBestFont(wchar_t character);
The callers should not be able to modify the underlying object pointed to by the returned pointer, this is the task of the class' methods/destructor.
The problem is that, most of the functions I want to pass the returned pointer to look like this:
void
XftDrawStringUtf8
(XftDraw *d,
XRenderColor *color,
XftFont *font, // It is not const
int x,
int y,
XftChar8 *string,
int len);
As you can see, even if the function does not need to change the data pointed to, the pointer is not const, and the only way to make it work is to use const_cast, which is never recommended, as far as I know.
This is just a single example, but there are many such issues in the real code.
I wonder, why are these legacy libraries built in such a way? Why don't they use const pointers when they actually should be const? And what is the best way to deal with such problems?
|
Is it necessarily bad to use const_cast when working with legacy libraries?
No.
It's generally bad to design code that requires a lot of const_cast, because it suggests you haven't thought very carefully about mutability.
You're using libraries that were written before const-correctness was much considered, and their design shortfalls are not your fault. Adapting to them is an entirely appropriate use of const_cast.
Freeing most of these resources is not just calling free(), special library functions should be used instead(::XftFontClose(), ::FcPatternDestroy() etc.,) so I don't see benefits of using smart pointers
You know you can use smart pointers with custom deleters, right? The benefit - that you don't have to implement five special methods in each class - is still there.
At most, consider writing a rule-of-zero wrapper type storing a std::unique_ptr (or std::shared_ptr, or whatever) with a custom deleter. It's a lot less typing, and way fewer opportunities for annoying bugs.
|
73,322,173
| 73,322,371
|
Runtime Error. Addition of unsigned offset
|
I was solving Increasing Subsequences in LeetCode and it is giving error continuously.
Tried in different IDEs with same test cases working every time. Even after brainstorming for an hour or two I was unable to find the error. Here is my C++ solution.
class Solution {
public:
vector<vector<int>>ans;
vector<vector<int>> findSubsequences(vector<int>& nums) {
vector<int>prev;
calc(nums,prev,0);
return ans;
}
void calc(vector<int>&v, vector<int>&prev, int k)
{
if(prev.size()>1)
ans.push_back(prev);
if(k<v.size())
{
unordered_set<int>s;
for(int i = k; i < v.size(); i++)
{
if((prev.size() == 0 && !s.count(v[i])) || (prev[prev.size()-1]<=v[i] && !s.count(v[i])))
{
prev.push_back(v[i]);
calc(v,prev,i+1);
s.insert(v[i]);
prev.pop_back();
}
}
}
}
};
Can anyone please help. Showing error in multiple test cases.
Here I am sharing one of the test cases :
[4,6,7,7]
Error : Line 1034: Char 34: runtime error: addition of unsigned offset to 0x602000000110 overflowed to 0x60200000010c (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:34
Here is the code which is working in IDEs.
#include <bits/stdc++.h>
using namespace std;
vector<vector<int>>ans;
void calc(vector<int>&v, vector<int>&prev, int k)
{
if(prev.size()>1)
ans.push_back(prev);
if(k<v.size())
{
unordered_set<int>s;
for(int i = k; i < v.size(); i++)
{
if((prev.size() == 0 && !s.count(v[i])) || (prev[prev.size()-1]<=v[i] && !s.count(v[i])))
{
prev.push_back(v[i]);
calc(v,prev,i+1);
s.insert(v[i]);
prev.pop_back();
}
}
}
}
int main() {
vector<int>nums{4,6,7,7};
vector<int>prev;
calc(nums,prev,0);
for(auto i : ans)
{
for(auto j : i)
cout<<j<<" ";
cout<<endl;
}
}
|
I was not able to reproduce the santizer message with the input in the question (see https://godbolt.org/z/j4rxGdoYb). However, this condition may wrap around an unsigned integer:
if((prev.size() == 0 && !s.count(v[i])) || (prev[prev.size()-1]<=v[i] && !s.count(v[i])))
When prev.size() == 0 but !s.count(v[i]) is false then prev.size() -1 subtracts 1 from an unsigned 0. As a consequence prev will be accessed out of bounds.
Either use std::ssize to get a signed size. Or make sure that prev[prev.size()-1] is only evaluated when prev.size() != 0.
Moreover, the member ans is never cleared. I expect to get the wrong answer when you call findSubsequences the second time. Also findSubsequences should not take the vector by non-const reference when it does not modify it.
|
73,322,232
| 73,322,828
|
Parse complex numbers with Boost::Spirit::X3
|
I would like to write a Boost::Spirit::X3 parser to parse complex number with the following possible input format:
"(X+Yi)"
"Yj"
"X"
My best attempt so far is the following (Open on Coliru):
#include <complex>
#include <iostream>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/spirit/home/x3.hpp>
#include <boost/spirit/home/x3/support/utility/error_reporting.hpp>
namespace x3 = boost::spirit::x3;
struct error_handler {
template <typename iterator_t, typename error_t, typename context_t>
auto on_error(iterator_t& /* iter */, const iterator_t& /* end */, const error_t& error,
const context_t& context) {
namespace x3 = boost::spirit::x3;
const auto& handler = x3::get<x3::error_handler_tag>(context).get();
handler(error.where(), "error: expecting: " + error.which());
return x3::error_handler_result::fail;
}
};
// -----------------------------------------------------------------------------
namespace ast {
template <typename T>
struct complex_number {
T real;
T imag;
operator std::complex<T>() {
return {real, imag};
}
};
} // namespace ast
BOOST_FUSION_ADAPT_STRUCT(ast::complex_number<double>, real, imag);
// -----------------------------------------------------------------------------
namespace parser {
const auto pure_imag_number = x3::attr(0.) > x3::double_ > x3::omit[x3::char_("ij")];
const auto pure_real_number = x3::double_ > x3::attr(0.);
struct complex_class : error_handler {};
const x3::rule<complex_class, ast::complex_number<double>> complex = "Complex number";
static const auto complex_def = ('(' > (x3::double_ > -(x3::double_ > x3::omit[x3::char_("ij")])) >> ')')
| pure_imag_number
| pure_real_number;
BOOST_SPIRIT_DEFINE(complex);
} // namespace parser
// =============================================================================
void parse(const std::string& str) {
using iterator_t = std::string::const_iterator;
auto iter = std::begin(str);
auto end = std::end(str);
boost::spirit::x3::error_handler<iterator_t> handler(iter, end, std::cerr);
const auto parser = boost::spirit::x3::with<boost::spirit::x3::error_handler_tag>(
std::ref(handler))[parser::complex];
std::complex<double> result{};
if (boost::spirit::x3::phrase_parse(iter, end, parser, x3::space, result) && iter == end) {
std::cout << "Parsing successful for:' " << str << "'\n";
} else {
std::cout << "Parsing failed for:' " << str << "'\n";
}
}
int main() {
for (const auto& str : {
"(1+2j)",
"(3+4.5j)",
"1.23j",
"42",
}) {
parse(str);
}
return 0;
}
Which gives the following results when running the compiled code (with GCC 12.1.1 and Boost 1.79.0):
Parsing successful for:' (1+2j)'
Parsing successful for:' (3+4.5j)'
Parsing successful for:' 1.23j'
In line 1:
error: expecting: N5boost6spirit2x314omit_directiveINS1_8char_setINS0_13char_encoding8standardEcEEEE
42
__^_
Parsing failed for:' 42'
What I am puzzled by is why the last alternative is not considered valid when parsing the string with only a real number within it.
|
So, @Eljay's comment is right...
The issue stems from the use of > instead of >> to allow the failures without triggering the error handler upon failure.
So to actually succeed, we need to use >> in these places:
const auto pure_imag_number = x3::attr(0.) >> x3::double_ >> x3::omit[x3::char_("ij")];
const auto pure_real_number = x3::double_ >> x3::attr(0.);
And only use > when we really want to abort immediately and report an error.
|
73,322,276
| 73,324,258
|
Qt passing a Value from one window to antother
|
I am quite new to programming, so hopefully someone can help me out. After calculating a value with a function and storing it into the variable with a setter, I want to call it in my viswindow.cpp to visualize it in a Graph. In the mainwindow the right value is calculated and stored by pressing a button, which also opens the viswindow. I tried to pass it with a pointer or with signals and slots, but it wouldn't work.
mainwindow.cpp:
double MainWindow::berechneFussabdruck(double strecke, int anzahl, double sfcWert)
{
if(strecke <= 1500 && strecke > 0){
double aequivalente_Co2 = (((sfcWert*3.116*50*(((0.0011235955)*(strecke-2*48.42))+0.233))*0.001)/anzahl);
setAequivalente(aequivalente_Co2);
}
else{
double aequivalente_Co2 = (((sfcWert*3.116*75*(((0.0011235955)*(strecke-2*208))+0.833))*0.001)/anzahl);
setAequivalente(aequivalente_Co2);
}
return aequivalente_Co2;
}
Button to open viswindow:
void MainWindow::on_pushButton_clicked()
{
MainWindow::berechneFussabdruck(strecke, anzahl, sfcWert);
visWindow = new VisWindow(this);
visWindow->show();
}
viswindow.cpp:
VisWindow::VisWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::VisWindow)
{
ui->setupUi(this);
...
*set0 << aequivalente_Co2 << aequivalente_Co2;
*set1 << 11.07 << 0;
*set2 << 0 << 0.49;
...
}
Thanks for helping!
|
Here are examples of:
Single time value transfer from MainWindow to VisWindow in constructor parameter.
Value update from MainWindow to VisWindow by slot-signal chain.
Value update from MainWindow to VisWindow by direct call of VisWindow->updateValue() slot as regular function.
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "viswindow.h"
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
void on_pushButton_3_clicked();
signals:
void updatevalue(const double value);
private:
Ui::MainWindow *ui;
VisWindow * m_viswindow;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow() {
delete ui;
}
void MainWindow::on_pushButton_clicked() {
m_viswindow = new VisWindow(12.34, nullptr);
connect(this, &MainWindow::updatevalue,
m_viswindow, &VisWindow::updateValue);
m_viswindow->show();
}
void MainWindow::on_pushButton_2_clicked() {
emit updatevalue(23.45);
}
void MainWindow::on_pushButton_3_clicked() {
m_viswindow->updateValue(45.67);
}
viswindow.h
#ifndef VISWINDOW_H
#define VISWINDOW_H
#include <QWidget>
namespace Ui {
class VisWindow;
}
class VisWindow : public QWidget
{
Q_OBJECT
public:
explicit VisWindow(const double value, QWidget *parent = nullptr);
~VisWindow();
public slots:
void updateValue(const double value);
private:
Ui::VisWindow *ui;
};
#endif // VISWINDOW_H
viswindow.cpp
#include "viswindow.h"
#include "ui_viswindow.h"
VisWindow::VisWindow(const double value, QWidget *parent) :
QWidget(parent),
ui(new Ui::VisWindow)
{
ui->setupUi(this);
ui->lblValue->setText(QString::number(value,'f',2));
this->setWindowTitle("VisWindow");
}
VisWindow::~VisWindow() {
delete ui;
}
void VisWindow::updateValue(const double value) {
ui->lblValue->setText(QString::number(value,'f',2));
}
|
73,322,362
| 73,322,363
|
Strange behavior of QTableView with text containing slashes
|
We recently ported a project from Qt 4.8 to Qt 5.15 (Qt 6 isn't an option for us yet due to dependencies).
We're finding that all our QTableViews behave strangely when an item's text contains slashes.
Here is a small program that demonstrates 2 issues:
#include <QTableWidget>
#include <QAbstractItemModel>
#include <QApplication>
#include <QDebug>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QTableWidget tbl;
tbl.setTextElideMode(Qt::ElideLeft);
tbl.setColumnCount(2);
tbl.setRowCount(argc-1);
for (int i = 1; i < argc; ++i)
{
tbl.setItem( i-1, 0, new QTableWidgetItem(QString::number(i)) );
tbl.setItem( i-1, 1, new QTableWidgetItem(argv[i]) );
}
tbl.show();
auto* pModel = tbl.model();
QString qstrMatch = "*single*file*";
QModelIndexList lst = pModel->match(pModel->index(0,1), Qt::DisplayRole, qstrMatch, -1, Qt::MatchWildcard);
qDebug() << lst.size() << "results";
for (const QModelIndex& idx : lst)
{
qDebug() << argv[1+idx.row()];
}
return app.exec();
}
Suppose we run this program with the following 4 strings:
/path/to/design/patterns/singleton_file.txt
/path/to/design/patterns/observer_file.txt
just_single_name_file_no_path.txt
drill a single 1/4 inch hole then file here
1) Text elision
In Qt 4, the Qt::ElideLeft is honored in all cases:
But in Qt 5, it seems to have a problem whenever the text contains a slash:
A colleague noticed that one table was still working as expected, and found that the thing it did differently was to use a custom delegate.
Sure enough, simply doing tbl.setItemDelegate(new QItemDelegate) on other tables fixes the issue for them as well.
But this doesn't seem to make any sense.
2) Text matching
In Qt 4, the call to the match function does return 3 results as expected.
In Qt 5, it only returns only 1 result - for the string not containing a slash.
Implementing the search with our own loop by using a QRegExp with Wildcard syntax works as expected, though.
https://doc.qt.io/qt-5.15/sourcebreaks.html does not provide any pointers as to what might have changed.
|
We were able to find the reasons behind and solutions for these issues after some digging in Qt 5's source code.
The two issues are unrelated.
1) Text elision
After studying the Qt source code for a while, I stumbled on this doc comment for QTableView::setWordWrap:
Note that even of wrapping is enabled, the cell will not be expanded to fit all text. Ellipsis will be inserted according to the current textElideMode.
Word wrapping is on by default, and its effect becomes clear only when you manually resize the row:
So the "..." is not for "horizontal" text width elision but for "vertical" word wrapped truncation.
The solution is to simply use: setWordWrap(false) on the QTableView.
The reason that using QItemDelegate made a difference appears to be that its implementation does simple elision before word wrapping, whereas QStyledItemDelegate (the default) first wraps and then only elides lines having very long words that could not be wrapped.
(It's not clear which part of this was done differently in Qt 4: Possibly slashes were not considered as valid word boundaries for wrapping.)
2) Text matching
The underlying difference is in the QAbstractItemModel::match function: using a QRegExp with Wildcard syntax earlier vs. QRegularExpression::wildcardToRegularExpression now.
As the documentation of the latter function states:
The transformation is targeting file path globbing, which means in particular that path separators receive special treatment.
This means that the text of every item is treated as a file path, where each * can match only within one single path component - it cannot span across slashes (it translates to something like [^/]* not just .*). So the wildcard pattern would need to have a particular number of slashes and stars in order to match the text.
So the only solution (if we choose to use QAbstractItemModel::match instead of rolling our own loops) appears to be to write our own wildcardToRegularExpression implementation that doesn't assume that the wildcards are being used for file paths, and hence does not treat path separators specially, and then use the Qt::RegularExpression match flag. Such a function would also be needed in other places where use of the now deprecated QRegExp with Wildcard syntax needs to be replaced with QRegularExpression.
|
73,322,490
| 73,322,649
|
Problem with virtual destructor when using template function delete
|
The following class (with virtual destructor) contains a templated operator delete:
struct S
{
virtual ~S() {}
template <typename... Args>
void operator delete(void* ptr, Args... args);
};
args can be empty, so I think S::operator delete can also be used when a usual delete is expected.
However (using g++), I get an error:
error: no suitable 'operator delete' for 'S'
Couldn't the "suitable 'operator delete'" be a template?
|
Nope! For much the same reason that template<typename T> S(T const&) doesn't define a copy constructor. A lot of C++'s special member functions are required to not be templates. In this instance, a templated operator delete is only selected for use from a placement-new expression.
The reasoning is basically "better safe than sorry". If templates could bind in these special cases, it would be way too easy to accidentally declare a special member function you didn't want to. In the copy constructor case, note how declaring such a constructor -- just so you could bind to, say, any integer type -- would spookily inhibit move construction of the class if it counted as a copy constructor.
And if that's actually what you want, of course, you can just declare the non-placement-delete, or copy constructor, or what-have-you, and have it delegate to the template. So the design here offers safety without overly constraining you.
|
73,322,716
| 73,324,272
|
SetClipboardData and new operator for HANDLE
|
#include <Windows.h>
int main()
{
HANDLE h = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, 4); //new char[4]{ "QWE" };
if (!h) return 1;
strcpy_s((char*)h, 4, "QWE");
OpenClipboard(0);
EmptyClipboard();
SetClipboardData(CF_TEXT, h);
CloseClipboard();
HeapFree(h, 0, 0);
return 0;
}
If I use new char[4]{ "QWE" }; instead of HeapAlloc() I recieve an error upon SetClipboardData() execution. Why does this work this way? Memory inspector for h shows the same result in both cases.
|
HeapAlloc() returns an LPVOID (void*) pointer, whereas new char[] returns a char* pointer. They are NOT the same type, and neither of them is a valid Win32 HANDLE to a memory object.
SetClipboardData() wants a valid HANDLE pointing to a memory object, but not just any type of HANDLE. Per the SetClipboardData() documentation:
If SetClipboardData succeeds, the system owns the object identified by the hMem parameter. The application may not write to or free the data once ownership has been transferred to the system, but it can lock and read from the data until the CloseClipboard function is called. (The memory must be unlocked before the Clipboard is closed.) If the hMem parameter identifies a memory object, the object must have been allocated using the [GlobalAlloc] function with the GMEM_MOVEABLE flag.
Neither HeapAlloc() nor new[] satisfy those requirements. You MUST use GlobalAlloc() instead, so the clipboard can properly take ownership of the memory object, eg:
#include <Windows.h>
int main()
{
HANDLE h = GlobalAlloc(GMEM_MOVABLE, 4);
if (!h) return 1;
char *pmem = (char*) GlobalLock(h);
if (!pmem) {
GlobalFree(h);
return 1;
}
strcpy_s(pmem, 4, "QWE");
GlobalUnlock(h);
if (OpenClipboard(NULL)) {
EmptyClipboard();
if (SetClipboardData(CF_TEXT, h))
h = NULL; // clipboard now owns it, don't free it!
CloseClipboard();
}
if (h) GlobalFree(h);
return 0;
}
At compile-time, HANDLE is just an alias for void*, and a char* pointer is implicitly convertible to void*, so the compiler will allow a HeapAlloc'ed LPVOID or a new[]'ed char* to be passed to SetClipboardData() without complaining. But at run-time, the OS expects the passed HANDLE to point at a valid movable global memory object, anything else will invoke undefined behavior.
|
73,323,652
| 73,323,724
|
class constructor building struct at the same memory location on every instantiation but other members in their own memory locations?
|
I have a class that when instantiated I build two standard struct members. my instantiation is independent and is in its own memory space every time I build one as is the name member, but the struct's built in the constructor are being given the same memory address every time and thus write over the previous instantiations struct? The pointer nor the struct is static any where so I don't see why this is occurring. If any one can spot my error please point it out.
-------------signal.h--------------
prama once
struct GenParams
{
float a;
float b;
};
class signal {
public:
signal();
~signal();
std::string sigName;
GenParams* mGP; //not static so every instance should have its own mGP I set to private as well but made no difference.
};
--------------------siganl.cpp------------------
#include signal.h
signal::signal()
{
GenParams GP; //every instance should have its own member GP at a unique mem location
// but instead GP is created at the same mem location
mGP = &GP; // mGP points to the same mem location every time the constructor is called
//fill struct with default values
GP.a = 0.0;
GP.b = 5.0;
}
signal::~signal()
{ }
--------------------interface.h--------------------
#include signal.h
class interface
{
public:
interface();
~interface();
std::string interName;
std::vector<signal*> sigList;
interface* iPtr;
unsigned int sigNum;
void newSignal();
--------------------------------interface.cpp----------------------
#include interface.h
interface::interface() : iPtr(this)
{ sigNum = 0;}
interface::~interface()
{
for (auto i : sigList)
delete i;
}
interface::newSignal()
{
signal* s = new signal;
//after this line returns the values are stored correctly in memory of struct
//during this line which does not reference the struct or the signal yet I see the structs
// memory get deallocated and go red as if something is writing to it and the values are gone
std::string newSName = this->interName + "sig" std::to_string(sigNum + 1);
//Here some values go back into the struct but they are bogus vals
s->sigName = newSName;
sigList.push_back(s);
//after adding to the list the sig instance has a name correctly written by the line above
//and a pointer it it but the pointer to the struct member mGP all instances point to the
//same memory location?? I don't understand how this is happening.
sigNum++;
}
|
This constructor invokes undefined behavior
signal::signal()
{
GenParams GP; //every instance should have its own member GP at a unique mem location
// but instead GP is created at the same mem location
mGP = &GP; // mGP points to the same mem location every time the constructor is called
//fill struct with default values
GP.a = 0.0;
GP.b = 5.0;
}
because the data member mGP
mGP = &GP;
is set to the address of the local variable GP with automatic storage diration
GenParams GP;
that will not be alive after exiting the constructor.
So the data member mGP will have an invalid value.
You should to allocate an object of the type GenParams dynamically or to have a data member of this type.
Pay attention to that in this line
std::string newSName = this->interName + "sig" std::to_string(sigNum + 1);
there is a typo. It seems you mean
std::string newSName = this->interName + "sig" + std::to_string(sigNum + 1);
|
73,324,557
| 73,334,325
|
Using return value of _spawnl() to get PID?
|
The documentation for the _spawn family of functions say they return a HANDLE when called with _P_NOWAIT.
I was hoping to use this handle with TerminateProcess(h, 1);
(In case the started process misbehaves.)
HANDLE h = (HANDLE) _spawnl(_P_NOWAIT, "C:\\temp\\hello.exe", NULL);
However, I don't understand the difference between these handles and the PID shown in the Task Manager.
The spawn function only ever returns very low values, like "248" and not what actually shows in Task Manager.
Can I use the return value of _spawn to kill a process and if so, how?
|
This did the trick:
auto process_handle = (HANDLE)_wspawnv(_P_NOWAIT, argv[1], &argv[1]);
auto procID = GetProcessId(ID);
thanks sj95126
|
73,325,231
| 73,325,268
|
Why is the iterator destructor implicitly called?
|
I'm creating an Iterator interface for my foo class, but while debugging, the iterator's destructor is being implicitly called after the first test.
// Setup for test
// First test
foo::Iterator itr = obj->begin();
int first_value = (itr++)->value; // Destructor called here
// Other tests with itr
I've gone through the call stack and noticed that every other call in this line is working as expected. The only problem seems to be that once every other call in the line is executed (postfix increment and arrow operator) the destructor is being implicitly called. Why is this happening?
|
postfix increment
Why do you think everyone tells you not to use it? A postfix increment is a prefix increment with an additional copy that has to get constructed and then destroyed for no reason.
This is correct code:
foo::Iterator itr = obj->begin();
int first_value = itr->value;
++itr;
|
73,325,235
| 73,325,667
|
How do I get the process ID of something in windows using c++
|
I am trying to get the procid of a process using the name of the process. The errors are talking about procEntry.szExeFile. However, I am getting the errors:
[{
"owner": "C/C++",
"code": "167",
"severity": 8,
"message": "argument of type \"WCHAR *\" is incompatible with parameter of type \"const char *\"",
"source": "C/C++",
"startLineNumber": 17,
"startColumn": 17,
"endLineNumber": 17,
"endColumn": 26
},{
"owner": "C/C++",
"code": "167",
"severity": 8,
"message": "argument of type \"WCHAR *\" is incompatible with parameter of type \"const char *\"",
"source": "C/C++",
"startLineNumber": 24,
"startColumn": 21,
"endLineNumber": 24,
"endColumn": 30
}]
Is there another way to get the process ID? I have tried reinstalling c++ libraries. I have also tried converting it but that didn't work either. Here is the code I am using:
#include <stdlib.h>
#include <iostream>
#include <string>
#include <windows.h>
#include <TlHelp32.h>
// Get process id from name
DWORD GetProcId(const char* procName)
{
PROCESSENTRY32 procEntry;
procEntry.dwSize = sizeof(procEntry);
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (hSnap == INVALID_HANDLE_VALUE)
return 0;
Process32First(hSnap, &procEntry);
if (!strcmp(procEntry.szExeFile, procName))
{
CloseHandle(hSnap);
return procEntry.th32ProcessID;
}
while (Process32Next(hSnap, &procEntry))
{
if (!strcmp(procEntry.szExeFile, procName))
{
CloseHandle(hSnap);
return procEntry.th32ProcessID;
}
}
CloseHandle(hSnap);
return 0;
}
int main()
{
// Get process id from name
DWORD procId = GetProcId("csgo.exe");
if (!procId)
{
std::cout << "Could not find process" << std::endl;
return 0;
}
// wait for key press
std::cout << "Press any key to continue" << std::endl;
std::getchar();
return 0;
}
|
You are using TCHAR-based macros, and you are compiling your project with UNICODE defined, so those macros map to the wchar_t-based APIs (ie, PROCESSENTRY32 -> PROCESSENTRY32W, Process32First -> Process32FirstW, etc). As such, the PROCESSENTRY32::szExeFile field is a wchar_t[] array. But, strcmp() expects char* strings instead, hence the compiler error you are getting.
Since your function takes in a const char* as input, you shouldn't be using the TCHAR APIs at all. Use the Ansi-based APIs instead, eg:
#include <iostream>
#include <string>
#include <cstring>
#include <windows.h>
#include <TlHelp32.h>
// Get process id from name
DWORD GetProcId(const char* procName)
{
PROCESSENTRY32A procEntry;
procEntry.dwSize = sizeof(procEntry);
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (hSnap == INVALID_HANDLE_VALUE)
return 0;
if (Process32FirstA(hSnap, &procEntry))
{
do
{
if (std::strcmp(procEntry.szExeFile, procName) == 0)
{
CloseHandle(hSnap);
return procEntry.th32ProcessID;
}
}
while (Process32NextA(hSnap, &procEntry));
}
CloseHandle(hSnap);
return 0;
}
int main()
{
// Get process id from name
DWORD procId = GetProcId("csgo.exe");
if (!procId)
{
std::cout << "Could not find process" << std::endl;
return 0;
}
// wait for key press
std::cout << "Press any key to continue" << std::endl;
std::getchar();
return 0;
}
Otherwise, change the code to use wchar_t strings and Wide-based APIs instead, eg:
#include <iostream>
#include <string>
#include <cwchar>
#include <windows.h>
#include <TlHelp32.h>
// Get process id from name
DWORD GetProcId(const wchar_t* procName)
{
PROCESSENTRY32W procEntry;
procEntry.dwSize = sizeof(procEntry);
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (hSnap == INVALID_HANDLE_VALUE)
return 0;
if (Process32FirstW(hSnap, &procEntry))
{
do
{
if (std::wcscmp(procEntry.szExeFile, procName) == 0)
{
CloseHandle(hSnap);
return procEntry.th32ProcessID;
}
}
while (Process32NextW(hSnap, &procEntry));
}
CloseHandle(hSnap);
return 0;
}
int main()
{
// Get process id from name
DWORD procId = GetProcId(L"csgo.exe");
if (!procId)
{
std::cout << "Could not find process" << std::endl;
return 0;
}
// wait for key press
std::cout << "Press any key to continue" << std::endl;
std::getchar();
return 0;
}
Stay away from TCHAR and its related macros if you can help it. They are a remnant from the Win9x/ME days when people were migrating code from ANSI to UNICODE. They really don't have a place in modern coding, as everything is now Unicode.
|
73,325,359
| 73,325,626
|
C++ Add constraints to a noexcept member function of template class
|
I have a 3D vector template class and I want to add a normalize member function to it.
Normalizing a vector only makes sense, if they use floating point numbers.
I want to use the c++20 requires syntax with the std::floating_point concept.
template<typename Type>
class vector3 {
[...]
vector3& normalize() requires std::floating_point<Type> noexcept;
}
But the compiler (gcc 11.2.0) gives me an error
error: expected ';' at end of member declaration
242 | vector3& normalize() requires (std::floating_point<Type>) noexcept;
| ^
| ;
|
noexcept is part of declarator, and requires-clause must come after declarator (dcl.decl)
so you need to write
// from @Osyotr in comment
vector3 & normalize() noexcept requires std::is_floating_point_v<Type>;
|
73,326,790
| 73,366,580
|
Visual Studio Code Intellisense doesn't show function documentation for C++
|
I followed this C/C++ for Visual Studio Code article from Microsoft to write C++ using Visual Studio Code. Unlike the article showing that intellisense provides documentation for member functions, it doesn't show me any. Same thing also happens in Visual Studio 2019 too. Here is a screenshot of how my intellisense looks.
What I tried to fix it so far:
Reinstall VSCode (deleted the app data as well)
Edit*
Configuration Files
c_cpp_properties.json
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
],
"windowsSdkVersion": "10.0.19041.0",
"compilerPath": "C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/VC/Tools/MSVC/14.29.30133/bin/Hostx64/x64/cl.exe",
"cStandard": "c17",
"intelliSenseMode": "windows-msvc-x64",
"cppStandard": "c++14"
}
],
"version": 4
}
settings.json
{
"files.associations": {
"xstring": "cpp"
}
}
tasks.json
{
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: cl.exe build active file",
"command": "cl.exe",
"args": [
"/Zi",
"/EHsc",
"/nologo",
"/Fe${fileDirname}\\${fileBasenameNoExtension}.exe",
"${file}"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$msCompile"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "Task generated by Debugger."
}
],
"version": "2.0.0"
}
|
The documentation shown in the mouseover tooltip is generated from the standard library source files configured to be used. The screenshot from the VS Code docs is from a setup using gcc's c++ standard library implementation, libstdc++, which has c++ comments containing that documentation. Since you are using Visual Studio, you are using Microsoft's implementation of the c++ standard library. Browsing through their headers, it seems that the Microsoft STL doesn't include such documentation comments.
You could ask a question on their discussion board to ask if there are good workarounds/alternatives, or (politely) ask why they don't maintain such documentation comments, or if they have plans to in the future.
I haven't used this, but you may be interested to try this VS Code extension: Guyutongxue.cpp-reference, which
is a tool to browse cppreference.com from within vscode, instead of going to the browser to do so. You can use this extension to search for library and methods documentation of the C++ standard.
|
73,327,414
| 73,327,471
|
How to stop strange symbols from being read in the beginning of a getline string C++?
|
I have this function that imports strings from a .txt file, but when I import using getline the very first string shows up with 3 strange symbols attached to the front. Every other string comes out fine.
I don't know if it's the file itself, but I tried making a new file and it still reads in the strange symbols.
I tried a similar function with different data from a different .txt file (still strings) and I had no strange symbols at all.
void SavagePlants::importInfo(std::fstream& importFile)
{
plants = new PlantCare[numPlants];
int i = 0;
while (getline(importFile >> std::ws, plants[i].species, '#')) {
getline(importFile, plants[i].sunlight, '#');
wrapText(plants[i].sunlight);
getline(importFile, plants[i].water, '#');
wrapText(plants[i].water);
getline(importFile, plants[i].temperature, '#');
wrapText(plants[i].temperature);
getline(importFile, plants[i].soil, '#');
wrapText(plants[i].soil);
getline(importFile, plants[i].fertilizer, '#');
wrapText(plants[i].fertilizer);
getline(importFile, plants[i].dormancy, '#');
wrapText(plants[i].dormancy);
++i;
}
}
This is what the output looks like for the first string:
Temperate Sundew
|
Your text file begins with a UTF-8 BOM (0xEF 0xBB 0xBF). You need to either:
create your UTF-8 text files without a BOM present.
just skip past those bytes before reading the rest of the file.
imbue() a UTF-8 locale into your fstream that knows how to recognize and ignore those bytes for you.
|
73,327,446
| 73,327,650
|
How do I write SFINAE for copy-list-init in a return statement, in a portable way?
|
I'm trying to make the following function SFINAE-friendly:
#include <utility>
template <typename T, typename ...P>
T foo(P &&... params)
{
return {std::forward<P>(params)...};
}
I can't put a return statement in a SFINAE context, but since this is an example of copy-list-initialization, I figured I could find a different example that is SFINAE-able.
There is T({...}), but only GCC accepts it:
template <typename T, typename ...P>
T foo(P &&... params)
requires requires{T({std::forward<P>(params)...});}
{
return {std::forward<P>(params)...};
}
#include <array>
struct A
{
A(int) {}
A(const A &) = delete;
A &operator=(const A &) = delete;
};
int main()
{
foo<std::array<A, 3>>(1, 2, 3); // Error: call to implicitly-deleted copy constructor of `std::array`.
}
There is also foo({...}) (a function call). GCC and Clang accept it, but MSVC rejects it:
template <typename T>
void accept(T) noexcept;
template <typename T, typename ...P>
T foo(P &&... params)
requires requires{accept<T>({std::forward<P>(params)...});}
{
return {std::forward<P>(params)...};
}
How do I work around the compiler bugs, and write this SFINAE in a portable way?
|
The second version works if you take const& parameter in accept:
template <typename T>
void accept(const T&) noexcept;
|
73,327,998
| 73,328,060
|
Exception when escaping "\" in Boost Regex
|
I'm always getting an exception when trying to escape a backslash like this:
boost::regex shaderRegex{ "test\\" };
Am I doing something wrong?
Unhandled exception at 0x00007FFD13034FD9 in project.exe: Microsoft C++
exception: boost::wrapexcept<boost::regex_error> at memory location
|
A literal backslash would be
boost::regex shaderRegex{ "test\\\\" };
In a C++ string, the characters \\ represent a single backslash character.
To represent a regex literal (escaped) backslash, you would need two of those.
If this looks confusing, you can also use a C++11 raw string literal.
boost::regex shaderRegex{ R"(test\\)" };
|
73,328,097
| 73,395,128
|
Implementing Compare for std::set
|
I have a struct that is just two ints that I want to store in std::set, while also taking advantage of its sorting properties. For example
struct Item
{
int order;
int value;
};
So I wrote a comparator
struct ItemCmp
{
bool operator()( const Item& lhs, const Item& rhs ) const
{
return lhs.order < rhs.order || lhs.value < rhs.value;
}
};
The intent is that Item should be sorted in the collection by ORDER first, and then by VALUE. If I put these Item in a vector and use std::sort, seems to be working as expected.
I also implemented unit tests for the cases in https://en.cppreference.com/w/cpp/named_req/Compare
However now this test case is failing:
std::set<Item, ItemCmp> stuff;
stuff.insert( {1, 1} );
stuff.insert( {1, 1} );
CHECK( stuff.size() == 1 );
The size of the set is 2, violating the contract of set. Where am I going wrong?
|
based on @retired-ninja 's comment, the answer is to ensure the comparator does proper lexicographical comparison. One shortcut to this is to leverage std::tuple's operators (see https://en.cppreference.com/w/cpp/utility/tuple/operator_cmp ) using this example:
return std::tie(lhs.order, lhs.value) < std::tie(rhs.order, rhs.value);
|
73,328,173
| 73,328,268
|
Function to print data type to debug console
|
While searching for any kind of function in could help printing data to debug console, I've found this function here on StackOverflow that can print almost any kind of data:
template <typename Arg, typename... Args>
void doPrint(Arg&& arg, Args&&... args)
{
std::stringstream out;
out << std::forward<Arg>(arg);
using expander = int[];
(void)expander {
0, (void(out << std::left << std::setw(20) << std::forward<Args>(args)), 0)...
};
OutputDebugStringA(out.str().c_str());
}
But it doesn't work when I try to pass a wstring to it, ex:
std::wstring color = L"blue";
doPrint("color: ", color);
I get this error:
Error C2679 binary '<<': no operator found which takes a right-hand operand of type 'std::wstring' (or there is no acceptable conversion)
Is it possible to also support wstring?
I tried to change std::stringstream to std::wstringstream, but now I get error on OutputDebugStringA():
void OutputDebugStringA(LPCSTR)': cannot convert argument 1 from 'std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>' to 'LPCSTR'
|
By default, you can't print a std::wstring to a char-based std::ostream, such as std::stringstream, because std::basic_ostream<char> (aka std::ostream) does not have an overloaded operator<< defined for std::wstring (or const wchar_t*).
You could define your own operator<< for that purpose, which converts a std::wstring to a std::string/char* using WideCharToMultiByte() or equivalent conversion, and then print that instead, eg:
std::ostream& operator<<(std::ostream &os, const std::wstring &wstr)
{
int len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), nullptr, 0, nullptr, nullptr);
if (len > 0) {
std::string str;
str.resize(len);
WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), str.data()/* or: &str[0] */, len, nullptr, nullptr);
os << str;
}
return os;
}
template <typename Arg, typename... Args>
void doPrint(Arg&& arg, Args&&... args)
{
std::stringstream out;
out << std::forward<Arg>(arg);
using expander = int[];
(void)expander {
0, (void(out << std::left << std::setw(20) << std::forward<Args>(args)), 0)...
};
OutputDebugStringA(out.str().c_str());
}
Online Demo
Otherwise, you need a wchar_t-based std::basic_ostream<wchar_t> (aka std::wostream) instead, such as std::wstringstream, using OutputDebugStringW() for the logging (unless you convert the output std::wstring to std::string to log with OutputDebugStringA()). Fortunately, std::basic_ostream<CharT> does have an overloaded operator<< for const char* strings (but not std::string) regardless of whether CharT is char or wchar_t, so std::wstringstream can print the pointer returned by std::string::c_str(), eg:
std::wostream& operator<<(std::wostream &os, const std::string &str)
{
os << str.c_str();
return os;
}
template <typename Arg, typename... Args>
void doPrint(Arg&& arg, Args&&... args)
{
std::wostringstream out;
out << std::forward<Arg>(arg);
using expander = int[];
(void)expander {
0, (void(out << std::left << std::setw(20) << std::forward<Args>(args)), 0)...
};
OutputDebugStringW(out.str().c_str());
}
Online Demo
|
73,328,905
| 73,329,269
|
Returning empty list to QImage
|
While browsing through some Qt code, I came across a function that is defined with a return type of QImage, but it's return value is an empty string {}. What does it mean? Couldn't figure it out from the searching I did.
Example:
QImage ExampleRenderer::addImage(QuickMapGL *mapItem, const QString &iconId)
{
if (mapItem == nullptr) {
return {};
}
const QImage image = iconProvider->requestImage(iconId, nullptr, QSize());
if(image.isNull()){
return {};
}
//
...
}
|
Modern C++ requires the compiler to deduce the (still static compile time) type without you needing to type it out. return is one of these cases, it's same as QImage{}, which is same as older style QImage(), meaning default constructed QImage value.
Here is some discussion on this {} initialization, called Uniform Initialization, and why it was added to C++.
|
73,328,916
| 73,329,010
|
How to set CMake build configuration in VSCode?
|
I'm using the CMake Tools extension in VSCode to build and run a C++ project on Windows.
Where do I set if the build configuration should be Debug or Release?
On Build, CMake Tools executes
"C:\Program Files\CMake\bin\cmake.EXE" --build c:/work/foobar/build --config Debug --target ALL_BUILD
How do I get the extension to build with --config Release?
|
The CMake Tools extension sets up a lot of goodies, including a status bar panel for configuring various aspects of your build(s). In the status line various panels provided by VSCode and extensions can be enabled/disabled. And example including the CMake Tools mini panels appears below:
Note: I am not running VS Code on a Windows machine; mine is MacOS, but the premise is the same.
Anyway, if you click on the portion that says CMake: [Debug]: Ready a select-variant list should open near the top of the IDE in the location you're probably familiar seeing the general Command Palette open. It will look like this:
It is here you can change your selection from one build configuration type to another.
You can also do this via the main command palette by doing the following:
Hit ctrl-shift-P (or cmd-shift-P on MacOS)
Type CMake. The list should filter to just CMake command options.
Scroll the list and choose CMake: Select Variant
The same aforementioned build variant options should present themselves.
|
73,329,387
| 73,329,399
|
how to control recursion in cpp
|
Hi I am building a project using cpp in that I am heavily using recursion but I am not able to get
void user1() {
avg=average(totall, dice);
if(avg>=3){
totallSum+=totall;
// cout<<name1<<" is safe! "<<name1<<"'s turn is score now "<<totallSum<<endl;
if(totallSum<point){
cout<<name1<<" is safe! "<<name1<<"'s turn is score now "<<totallSum<<endl;
}
else {
user1totall+=totallSum;
break;
}
}
else{
totallSum=0;
user2(name1, name2,point,5,0,user1totall,user2totall,++turn2);
}
user2(name1, name2,point,dice,totallSum,user1totall,user2totall,++turn2);
}
this is the small snippet of the code I wrote
here the issue is that in the else block where the user2 function is being called it works completely fine but when it is executed completely it don't exit this user1 function instead it agains call the user2 function on the second last line
can anyone please tell how to resolve this issue
|
It's because the memory is stored in stack (Last in First out).
When its calling user2 function first time then the program will complete its execution first due to Stack memory
after it has executed user2 function then it will continue again back to user1 and move next where it is again calling user2.
To resolve this error change user1 return type from void to int
and when you are calling user2 function
after that line add
return 0;
it will work completely fine
|
73,329,574
| 73,338,215
|
MSVC Error C3015 (bad OpenMP for loop) but not an obvious mistake
|
I'm compiling some C++ code in Visual Studio 2022. I'm using /std:c++17 /O2 /permissive- /openmp:llvm /MP /arch:AVX2 as compiler settings. I'm getting the compiler error
C3015 initialization in OpenMP 'for' statement has improper form
However, I'm feeling like this might be a compiler bug (possibly with /openmp:llvm), since I can't even make the simplest OpenMP for loop work in this context. The for loop lives inside a lambda that's defined inside a template function that lives in a namespace (outside any class or struct) in a header file. Something like:
namespace Foo {
template <typename Func>
void f(Func work, const int beta, bool check = false) {
auto mylambda = [](std::vector<double>& y, double a) {
#pragma omp parallel for
for (int test = 0; test < 0; test++)
printf("Hello C3015\n");
};
work();
}
}
I have seen C3015 in the past when trying to use long (signed/unsigned) loop variables, but this is not that. Also, the exact code compiles fine under gcc, so this is something specific about MSVC behavior. There are other OpenMP for loops in this header file (in other functions etc.) that do not throw this error.
I'm just wondering whether there is some usage mistake I'm making, or if there is some workaround. Or if this is an unavoidable compiler bug, at least how to report such a thing and maybe get it fixed.
|
As suggested in the comment by @Jerry Coffin, this is a compiler bug that is a regression between x64 msvc 19.31 and 19.32. It turns out this bug has already been reported to Microsoft and a fix is pending release (I would guess in the next minor MSVC update).
|
73,329,767
| 73,329,998
|
Google Test Expect Call Function
|
I am trying to learn google test framework, and I came across an example here. I have something similar to "accepted solution", but I wanted to test it while having class methods as protected.
class GTEST_static_class {
protected:
virtual void display() { std::cout << "inside the GTEST_static_class:: display\n"; }
virtual ~GTEST_static_class() {}
};
class GTest_static_example : public ::testing::Test {
public:
void call_display(GTEST_static_class *instance) {
instance->display();
std::cout << "display called from GTest_static_example\n";
}
};
How do I modify that piece of code (accepted solution) to make it work while having class like mentioned above?
|
Add a friend class GTest_static_example:
class GTEST_static_class {
protected:
virtual void display() { std::cout << "inside the GTEST_static_class:: display\n"; }
virtual ~GTEST_static_class() {}
friend class GTest_static_example;
};
|
73,329,772
| 73,330,076
|
How to create a friend function for template base class with constexpr
|
I want to create a overloaded operator<< for a template base class, that calls the toString function for the child class. The issue is that the toString function of the child class is constexpr, which mean I cannot make it a virtual function of the base class. Here is what I want to do:
template<typename T>
class Base {
public:
Base(const T& t) : m_val(t) {}
friend std::ostream & operator<<(std::ostream &os, const Base& base);
protected:
const T m_val;
};
class Child1 : public Base<SomeLiteralType1> {
public:
using Base::Base;
constexpr const char* toString() {
const char* LUT[] = {"aa", "bb"};
return LUT[m_val]; // <-- assume T can be converted to int
}
};
class Child2 : public Base<SomeLiteralType2> {
...
};
std::ostream & operator<<(std::ostream &os, const Base& base) {
// cannot access toString() since it is not defined in Base
// maybe using dynamic_cast?
}
int main() {
Child1 c1 = {...};
Child2 c2 = {...};
// I want to be able to use << directly:
std::cout<<c1<<std::endl;
std::cout<<c2<<std::endl;
}
|
Use CRTP to get access to the derived class:
template <typename T, typename Derived>
class Base {
...
friend std::ostream& operator<<(std::ostream& os, const Base& base) {
return os << static_cast<const Derived&>(base).toString();
}
...
};
class Child1 : public Base<int, Child1> {
...
};
Compiler Explorer
|
73,329,912
| 73,329,999
|
Whats the difference between a range of a set(a,b) and union of all elements of sets in (a,b)?
|
Beginner here. Wrote a program to check if entered alphabet is lowercase or upppercase. (Practising if/else questions)
I thought of two methods:
Range method-getting the desired result
Union method-not getting the desired result
Here is the code,
if (enteredAlphabet>='a' && enteredAlphabet <='z')
{
cout<<enteredAlphabet<<" is lowercase.";
}
and
if (enteredAlphabet==('a'||'b'||'c'||'d'||'e'||'f'||'g'||'h'||'i'||'j'||'k'||'l'||'m'||'n'||'o'||'p'||'q'||'r'||'s'||'t'||'u'||'v'||'w'||'x'||'y'||'z'))
{
cout<<enteredAlphabet<<" is lowercase.";
}
|
The expression 'a'||'b'||... is actually a short-hand for ('a' != 0) || ('b' != 0) || ....
The result of the expression will always be the boolean value true.
Since true can be converted to the integer value 1 your comparison is really the same as enteredAlphabet == 1. This comparison will likely never be true.
What you actually should use is std::islower:
if (std::islower(enteredAlphabet)) { /* Is lower case letter */ }
|
73,329,974
| 73,330,041
|
Why is max_element not showing the largest string in vector C++?
|
In the code below I attempt to print the largest std::string in a std::vector using std::max_element.
I expected the output of the code below to be:
Harmlessness
The actual output I got is:
This
The code:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main(){
vector <string> strlist;
strlist.push_back("This");
strlist.push_back("Harmless");
strlist.push_back("Harmlessness");
cout << *max_element(strlist.begin(), strlist.end());
return 0;
}
My question:
Can you explain why the code produced the actual output above and not the one I expected ?
|
The default comparator for std::string does an lexicographic comparisson (see: std::string comparators).
The string "This" comes later in this order than any string starting with "H".
You can use another overload of std::max_element that accepts an explicit comparator argument:
template<class ForwardIt, class Compare> constexpr
ForwardIt max_element( ForwardIt first, ForwardIt last, Compare comp);
If you want to compare strings by length, you can use:
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector <std::string> strlist;
strlist.push_back("This");
strlist.push_back("Harmless");
strlist.push_back("Harmlessness");
// Use an explicit comparator, in this case with a lambda:
std::cout << *max_element(strlist.begin(), strlist.end(),
[](std::string const& a, std::string const& b) {return a.length() < b.length(); });
return 0;
}
Output:
Harmlessness
Side note: better to avoid using namespace std - see here Why is "using namespace std;" considered bad practice?.
|
73,330,007
| 73,330,695
|
C++ conditionally call functions based on type of the template parameter
|
Suppose that I have a couple of functions to process different types of arguments. For example processInt for processing int variables and processString for processing std::string variables.
int processInt(int i)
{
return i;
}
string processString(string s)
{
return s;
}
And, I have a template function called foo which takes either of int or std::string as argument. And inside this function I need to conditionally call the processInt or processString based on the variable type sent to it as the argument. The foo function would look like this:
#include <type_traits>
template<typename T>
T foo(T value)
{
T variable;
if (std::is_same<T, int>::value)
{
variable = processInt(value);
}
else if (std::is_same<T, string>::value)
{
variable = processString(value);
}
return variable;
}
int main() {
string s = "Abc";
int i = 123;
cout << foo(s) << " " << foo(i) << endl;
}
However, with the above foo function I get the following errors:
error: no matching function for call to 'processInt'
variable = processInt(value);
^~~~~~~~~~
note: in instantiation of function template specialization 'foo<std::__cxx11::basic_string<char> >' requested here
cout << foo(s) << " " << foo(i) << endl;
^
note: candidate function not viable: no known conversion from 'std::__cxx11::basic_string<char>' to 'int' for 1st argument
int processInt(int i)
^
error: no matching function for call to 'processString'
variable = processString(value);
^~~~~~~~~~~~~
note: in instantiation of function template specialization 'foo<int>' requested here
cout << foo(s) << " " << foo(i) << endl;
^
note: candidate function not viable: no known conversion from 'int' to 'std::__cxx11::string' (aka 'basic_string<char>') for 1st argument
string processString(string s)
^
Source code: https://godbolt.org/z/qro8991ds
How could I do this correctly to conditionally call functions based on type of the template parameter in generic functions?
EDIT
I like to use a single foo function without overloading or specializations as otherwise there may be some code duplications. The foo function may have lot of lines. But, the difference between code for int and string will be a single line.
|
All branches should be valid, even if branch is not taken.
C++17 has if constexpr which would solve your issue
template<typename T>
T foo(T value)
{
T variable;
if constexpr (std::is_same<T, int>::value)
{
variable = processInt(value);
}
else if constexpr (std::is_same<T, string>::value)
{
variable = processString(value);
}
return variable;
}
For pre-c++17, you might use overload to obtain similar results (tag dispatching for more complex cases):
int foo(int value)
{
return processInt(value);
}
std::string foo(const std::string& value)
{
return processString(value);
}
template <typename T
// possibly some SFINAE to allow some conversion with above functions
/*, std::enable_if_t<std::is_constructible<std::string, T>, bool> = true */>
T foo(T value)
{
return T{};
}
|
73,330,290
| 73,331,662
|
From one argument make two - at compile time
|
I'm writing a special print function that produces a cstdio printf - statement at compile time. The idea is basically that you invoke a function special_print() with a variadic parameter list and the function will assemble the necessary printf - statement at compile time. Here's what I've got:
#include <cstdio>
#include <string_view>
// how to implement "expand" from below?
template <typename... Ts>
constexpr const char* cxpr_format = /* ... this one I've already figured out */
template <typename... Ts>
void special_print(Ts... arg)
{
printf(cxpr_format<Ts...>, expand(arg)...);
// should expand to printf("%.*s%d", string_view.size(), string_view.data(), int) with below function call
}
int main()
{
std::string_view strview = "hello world";
int integer = 2;
special_print(strview, integer);
}
I've already figured out the part for creating my format string - that one is out of the question. But now comes the problem: In case when I've got a string_view passed in as an argument, I would need to conditionally expand it to two arguments to printf: one for the initial char pointer and one for the size which goes together with the %.*s format specifier. And this is the real crux. Can this be done somehow in C++ (at compile time)?
Note: Before any further questions arise I would like to point out that I have no idea on how to do this in C++ and this is my question. Every approach will be gladly taken into account!
|
My initial thought is to forward each arg through a tuple, and then "varags apply" in the call.
template <typename T>
auto expand(T&& t) { return std::forward_as_tuple<T>(t); }
auto expand(std::string_view s) { return std::tuple<int, const char *>(s.size(), s.data()); }
template <typename... Ts>
void special_print(Ts... arg)
{
using expanded = decltype(std::tuple_cat(expand(arg)...));
[]<std::size_t... Is>(auto tup, std::index_sequence<Is...>)
{
printf(cxpr_format<Ts...>, std::forward<std::tuple_element_t<Is, expanded>>(std::get<Is>(tup))...);
}(std::tuple_cat(expand(arg)...), std::make_index_sequence<std::tuple_size_v<expanded>>{});
// should expand to printf("%.*s%d", string_view.size(), string_view.data(), int) with below function call
}
See it on coliru
|
73,330,658
| 73,345,749
|
Cuda lambda vs functor usage
|
I've got a simple function in CUDA using a functor
struct MT {
const float _beta1;
const float _mb1;
MT(const float beta1, const float mb1) : _beta1(beta1), _mb1(mb1) { }
__device__
float operator()(const float& op, const float& gradient) {
return _beta1 * op + _mb1 * gradient;
}
};
void example(const thrust::device_vector<float>& gradients, thrust::device_vector<float>& d_weights)
{
thrust::transform(_mt.begin(), _mt.end(), gradients.begin(), _mt.begin(), MT(_beta1, _mb1));
}
However this equivalent example crashes (complies fine with --extended-lambda flat). Is there another flag or different way of expressing this to make it run. Functors are fine, but lambda's look neater.
void example_crash(const thrust::device_vector<float>& gradients, thrust::device_vector<float>& d_weights)
{
thrust::transform(_mt.begin(), _mt.end(), gradients.begin(), _mt.begin(), [this](const float& op,const float& gradient) { return _beta1 * op + _mb1 * gradient; });
}
Error is
Exception thrown at 0x00007FFA833D4FD9 in Optioniser.exe: Microsoft C++ exception: thrust::system::system_error at memory location 0x00000031ED7FCDD0.
Exception thrown: 'System.Runtime.InteropServices.SEHException' in AARC.Optimisation.dll
An exception of type 'System.Runtime.InteropServices.SEHException' occurred in AARC.Optimisation.dll but was not handled in user code
External component has thrown an exception.
|
Your example and example_crash functions don't make sense to me because I don't know what _mt is and you don't seem to be using d_weights.
If we fix that, then there are at least a couple issues with your lambda, one of them being there is no __device__ decoration (which is necessary, here).
Making various changes, and fixing things you haven't shown, this works for me:
$ cat t2093.cu
#include <thrust/device_vector.h>
#include <thrust/transform.h>
#include <thrust/host_vector.h>
#include <thrust/copy.h>
#include <iostream>
struct MT {
const float _beta1;
const float _mb1;
MT(const float beta1, const float mb1) : _beta1(beta1), _mb1(mb1) { }
__device__
float operator()(const float& op, const float& gradient) {
return _beta1 * op + _mb1 * gradient;
}
};
const float _beta1 = 1.0f;
const float _mb1 = 1.0f;
void example(const thrust::device_vector<float>& gradients, thrust::device_vector<float>& _mt)
{
thrust::transform(_mt.begin(), _mt.end(), gradients.begin(), _mt.begin(), MT(_beta1, _mb1));
};
void example_crash(const thrust::device_vector<float>& gradients, thrust::device_vector<float>& _mt)
{
thrust::transform(_mt.begin(), _mt.end(), gradients.begin(), _mt.begin(), [=] __device__ (const float& op,const float& gradient) { return _beta1 * op + _mb1 * gradient; });
};
const int len = 1000;
int main(){
thrust::device_vector<float> g1(len, 1.0f);
thrust::device_vector<float> mt1(len, 2.0f);
example(g1, mt1);
thrust::host_vector<float> h_mt1 = mt1;
thrust::copy_n(h_mt1.begin(), 2, std::ostream_iterator<float>(std::cout, ","));
std::cout << std::endl;
thrust::device_vector<float> g2(len, 1.0f);
thrust::device_vector<float> mt2(len, 2.0f);
example_crash(g2, mt2);
thrust::host_vector<float> h_mt2 = mt2;
thrust::copy_n(h_mt2.begin(), 2, std::ostream_iterator<float>(std::cout, ","));
std::cout << std::endl;
}
$ nvcc -o t2093 t2093.cu --extended-lambda
$ compute-sanitizer ./t2093
========= COMPUTE-SANITIZER
3,3,
3,3,
========= ERROR SUMMARY: 0 errors
$
|
73,330,823
| 73,331,413
|
ListView_GetNextItem always returning 0
|
I have some code that currently causes an infinite loop and I'm unable to find an reason as to why.
The code is designed to set bit-flags on an integer based on items that are selected in the listbox.This is handled by the case statement within the While loop.
I've followed the code through on a debugger and the value of selectedItem never changes. The handle to the listbox appears to be valid and is populated using the same handle.
I've tried using both the SendMessage function and ListView_GetNextItem macro, former is commented out in my code.
Any help would be appreciated, I'm assuming I'm missing something obvious here!
Edit:
I was basing this loop off the one seen here:
win32 retrieve index of all selected items from listview
int getTypeStatus()
{
int retVal =0;
//int selectedItem = SendMessage(lstFileStatus, LVM_GETNEXTITEM, (WPARAM)-1, MAKELPARAM(LVIS_SELECTED,0));
int selectedItem = ListView_GetNextItem(lstFileStatus,-1, LVNI_SELECTED);
while (selectedItem != -1)
{
switch (selectedItem){
case 0:
retVal = retVal | NOT_VERIFIED;
break;
case 1:
retVal = retVal | IRRELEVANT;
break;
case 2:
retVal = retVal | NOT_IN_LIST;
break;
case 3:
retVal = retVal | CONFIRMED;
break;
case 4:
retVal = retVal | NOT_CONFIRMED;
break;
case 5:
retVal = retVal | NEWLY_IDENTIFIED;
break;
case 6:
retVal = retVal | MISMATCH_DETECTED;
break;
}
selectedItem = ListView_GetNextItem(lstFileStatus,selectedItem, LVNI_SELECTED);
}
return retVal;
}
Edit: Also included code for creating control and populating (which works)
lstFileStatus = CreateWindowEx(0,"ListBox","",WS_CHILD|WS_VISIBLE|LBS_NOTIFY|WS_BORDER|LBS_EXTENDEDSEL,LeftHandStartX,TypeLineY,130,170,hwnd,(HMENU)IDC_LBX_TYPESTATUS,GetModuleHandle(NULL),0);
if (!lstFileStatus) {outputControlOutputError("lstFileStatus");}
for (int i=0;i<numTypeStatus;i++)
{
SendMessage(lstFileStatus,LB_ADDSTRING,0,(LPARAM)arrayTypeStatus[i]);
}
|
LVM_GETNEXTITEM is listview control message, but your control is a listbox. They're different controls and the messages aren't interchangable.
To get the selected items from a multi-select listbox you need to use LB_GETSELCOUNT to get the number of selections, allocate an array of ints that size, and then use LB_GETSELITEMS to get the selection indices.
|
73,331,060
| 73,342,337
|
What does .word 0 mean in ARM assembly?
|
I'm writing a C++ state machine for Cortex-M4.
I use ARM GCC 11.2.1 (none).
I'm making a comparison between C and C++ output assembly.
I have the following C++ code godbolt link
struct State
{
virtual void entry(void) = 0;
virtual void exit(void) = 0;
virtual void run(void) = 0;
};
struct S1 : public State
{
void entry(void)
{
}
void exit(void)
{
}
void run(void)
{
}
};
S1 s1;
The assembly output is:
S1::entry():
bx lr
S1::exit():
bx lr
S1::run():
bx lr
vtable for S1:
.word 0
.word 0
.word S1::entry()
.word S1::exit()
.word S1::run()
s1:
.word vtable for S1+8
The only difference from C version of this code is the 2 lines .word 0:
vtable for S1:
.word 0
.word 0
What does that mean and what does it do?
Here's the C version of the code above I wrote.
godbolt link
|
The C++ ABI for ARM and the GNU C++ ABI define which entries must appear in the virtual table.
In the case of your code, the first two entries are the offset to the top of the vtable and the typeinfo pointer. These are zero for now, but may be overwritten if required (eg: if a further derived class is made).
|
73,331,374
| 73,331,427
|
How does std::unordered_map differentiate between values in the same bucket?
|
I know that std::unordered_map handles key hash collisions by chaining keys with the same hash in a bucket (I think using a linked list). The question I have is how does it know which value, in the same bucket, corresponds to which key?
The naive idea I have is that each value is stored in a std::pair, is this how it is done?
|
Yep, that's basically how it's done. Keep in mind that the key is part of the data. One of the things you can do with a map is iterate through its key/value pairs. This would be impossible, even with perfect hashing, if the key itself were not stored.
|
73,331,712
| 73,332,465
|
How to elegantly flip a BOOL, without a warning?
|
I want to simply flip a BOOL variable, but this generates a lnt-logical-bitwise-mismatch warning.
Is there an elegant solution to this?
BOOL bCloseButtons = FALSE;
bCloseButtons = !bCloseButtons; // Intellisense generate a logical-bitwise mismatch
bCloseButtons = bCloseButtons ? FALSE : TRUE; // works, but not elegant in my eye
CButton m_btnPumpP1;
BOOL bLocked = FALSE;
m_btnPump_P1.EnableWindow(!bLocked); // Intellisense generate a logigal-bitwise mismatch
m_btnPump_P1.EnableWindow(!((bool)bLocked)) // horrible, not readable
|
Use a bool value in your code instead. Flipping a bool is a simple matter of applying the unary !-operator, e.g. value = !value;.
Passing a bool value into an API that expects a BOOL (aka int) value implicitly performs integral promotion from bool to int. This is well defined and will not trigger any warnings.
Likewise, if a BOOL return value needs to be converted to a value of type bool, that conversion is also implicit. The value 0 becomes false, and all other values become true. This will not raise any warnings either. If code wants to be explicit about this conversion the following expression produces a bool value following the implicit conversion rules: value_abi != FALSE.
A bit of rationale: BOOL is a type alias for a signed 32-bit integer. It exists solely to describe an API in a way that's ABI-stable, so that code compiled today will continue to run a decade from now without having to be recompiled. It is strictly there to establish a binary contract between the caller and the implementation of a function.
It's not generally useful to keep those ABI types in client code. If you are modeling a flag in C++, then clearly a boolean value is the most appropriate type. When it comes time to pass this value into an API you would then convert it to the expected ABI type. In case of a bool value this is done automatically as part of the integral type promotion rules of the C++ programming language. At other times you may have to explicitly perform the conversion, though that is extremely rare.
|
73,332,157
| 73,496,996
|
Visual Studio 2022 intellisense cannot find Openssl (ARM64 - Makefile project - SSH - Ubuntu)
|
(Only to be clear, this question is regarding Intellisense only)
Here is my developing scenario:
Visual Studio 2022 (Enterprise edition, 64 bits)
C++ project (Run by SSH to a Raspberry Pi 4 - ARM64 using Ubuntu 20.04 server)
Project is a Makefile project (not CMake).
The code compiles and runs in the Raspberry Pi (via SSH), but the problem is with Visual Studio Intellisense that cannot find the OpenSSL files.
I ran the tutorial here (https://kontext.tech/article/594/microsoft-vcpkg-c-library-manager) and installed vcpkg
vcpkg install openssl:arm64-windows
and ran the instruction to integrate to Visual Studio
vcpkg integrate install
and everything seems to be installed correctly,
PS C:\vcpkg> .\vcpkg.exe integrate install
Applied user-wide integration for this vcpkg root.
CMake projects should use: "-DCMAKE_TOOLCHAIN_FILE=C:/vcpkg/scripts/buildsystems/vcpkg.cmake"All MSBuild C++ projects can now #include any installed libraries. Linking will be handled automatically. Installing new libraries will make them instantly available.
but as this is a Makefile project (and not CMake), it still seems to have the problem with Intellisense.
Could you please help me to determine how to make Visual Studio to finally find the OpenSSL files?
Thank you.
|
I made progress in solving the problem in an unexpected way. As the project built successfully in the remote machine, I ignored the Intellisense problems for a while. But one day I connected to another machine and there were no problems! Intellisense found all the files.
The machine with problems had Ubuntu 20.04 and the other one Raspbian OS. The difference was that I installed OpenSSL using apt in Ubuntu,
sudo apt -y install libssl-dev
but I compiled the OpenSSL source code in the Raspbian OS. (https://www.linuxtuto.net/blog/how-to-install-OpenSSL-3-on-Ubuntu-20-04) and (https://nextgentips.com/2022/03/23/how-to-install-openssl-3-on-ubuntu-20-04/)
So I knew the problem was due to the headers.
I compiled OpenSSL from source in Ubuntu, and it didn't work. But I had a third machine with Ubuntu 22.04 and did the same, and it worked. So I knew the exact problem: Visual Studio didn't bring the headers after an initial SSH connection was made.
Solution:
[IMPORTANT] Download OpenSSL source code using the tutorials I linked above, and compile it in your Linux machine (mine was an upgrade from 1.1.1f to 3.0.5).
Go to C:\Users[Your user]\AppData\Local\Microsoft\Linux
Depending on your Visual Studio version (mine is 2022), you will have a folder structure. Search around and you will find an XML file with your connection information (in my case, it was in User Data\3.0\store.xml)
Open the XML. You will have a list of all the SSH connections that version of Visual Studio has made to remote machines.
Check in the HeaderCache\1.0 folder. You will find folders with random numbers, and they match the connections from the XML. Identify the problematic connection.
Inside Visual Studio, delete that SSH connection. (It should also disappear from the XML, but it DOES NOT automatically delete the folder, so this is why the problem happened in the first place).
Delete the associated folder inside the HeaderCache\1.0 you found in step 4.
Recreate the SSH connection inside Visual Studio. It should appear in the XML and a new folder must be created inside HeaderCache\1.0.
Check inside the new folder. Go to the subfolder usr\include. There should be an OpenSSL folder.
Change the configuration of your solution in Visual Studio to use the new SSH connection.
Problem solved!
Edit: Sometimes you must delete your Visual Studio Configuration (inside the Configuration manager). After you delete the problematic configuration, in some cases Visual Studio still shows it inside the project properties. If that is your case, you must:
Open the Package Manager Console (Tools -> Nuget Package Manager -> Package Manager Console)
Run the command:
Get-Project -All | Foreach { $_.ConfigurationMAnager.DeleteConfigurationRow("Name of your configuration with quotes") }
And that's it!
|
73,332,564
| 73,332,662
|
What is the time complexity of new and delete for primitive VS user-defined data types?
|
From what I gathered, it depends on the implementation of the constructors and destructors for user-defined data types.
I was wondering if there is set time complexity / any guarantees for primitive data types allocation?
|
No, there's no such guarantee. Lacking constructors, the time complexity is entirely due to the underlying operator new which has to find free heap storage.
Note that some operator new call is also needed for classes, but this could be either the global ::operator new or a class member. In both cases, it too needs to find free heap storage.
|
73,332,642
| 73,355,270
|
C++ with Crow, CMake, and Docker
|
Goal
I would like to compile an Crow Project with CMake and deploy it in a docker container.
Code
So far, I compiled in Visual Studio and installed Crow via VCPKG similar to this Tutorial.
example main.cpp from Crow website:
#include "crow.h"
//#include "crow_all.h"
int main()
{
crow::SimpleApp app; //define your crow application
//define your endpoint at the root directory
CROW_ROUTE(app, "/")([](){
return "Hello world";
});
//set the port, set the app to run on multiple threads, and run the app
app.port(18080).multithreaded().run();
}
I want to build my docker image with docker build -t main_app:1 . and then run a container with docker run -d -it -p 443:18080 --name app main_app:1.
Therefore, I considered something similar like this:
Dockerfile:
FROM ubuntu:latest
RUN apt-get update -y
RUN apt-get upgrade -y
# is it necessary to install all of them?
RUN apt-get install -y g++ gcc cmake make git gdb pkg-config
RUN git clone --depth 1 https://github.com/microsoft/vcpkg
RUN ./vcpkg/bootstrap-vcpkg.sh
RUN /vcpkg/vcpkg install crow
CMakeLists.txt:
cmake_minimum_required(VERSION 3.8)
project(project_name)
include(/vcpkg/scripts/buildsystems/vcpkg.cmake)
find_package(Crow CONFIG REQUIRED)
add_executable(exe_name "main.cpp")
target_link_libraries(exe_name PUBLIC Crow::Crow)
Questions
However, obviously this is not complete and thus will not work. Hence, I would like to know how a proper (and simple) Dockerfile and CMakeLists.txt would look like for this main.cpp?
Is it possible to create my image without VCPKG? I am a little bit concerned about my image and container size, here.
How would it work with the crow_all.h header only file?
Is it possible to build an image from an already compiled name.exe, as well - so I won't have to compile anything while building the image?
Since this ought to be a minimal example, would there be any conflicts with a file structure like this:
docker_project
|__Dockerfile
|__CMakeLists.txt
|__header.hpp
|__class.cpp
|__main.cpp
Thanks for your help :)
|
After further research and testing I could solve this issue on two ways:
Crow.h Project compiled with CMake in Docker container
Dockerfile
# get baseimage
FROM ubuntu:latest
RUN apt-get update -y
RUN apt-get upgrade -y
# reinstall certificates, otherwise git clone command might result in an error
RUN apt-get install --reinstall ca-certificates -y
# install developer dependencies
RUN apt-get install -y git build-essential cmake --no-install-recommends
# install vcpkg package manager
RUN git clone https://github.com/microsoft/vcpkg
RUN apt-get install -y curl zip
RUN vcpkg/bootstrap-vcpkg.sh
# install crow package
RUN /vcpkg/vcpkg install crow
# copy files from local directory to container
COPY . /project
# define working directory from container
WORKDIR /build
# compile with CMake
RUN bash -c "cmake ../project && cmake --build ."
# run executable (name has to match with CMakeLists.txt file)
CMD [ "./app" ]
Docker directory would look like this:
Docker
|__vcpkg
|__ ...
|__project
|__CMakeLists.txt
|__main.cpp
|__build
|__app
|__ ...
CMakeLists.txt
cmake_minimum_required(VERSION 3.8)
project(project)
# full path from root directory
include(/vcpkg/scripts/buildsystems/vcpkg.cmake)
find_package(Crow CONFIG REQUIRED)
add_executable(
app
main.cpp
)
target_link_libraries(app PUBLIC Crow::Crow)
build Docker image in local directory
project
|__Dockerfile
|__CMakeLists.txt
|__main.cpp
Navigate to project folder in shell and run docker build -t image_name:1 . to build the Docker image and run Docker container with docker run -d -it --rm --name container_name -p 443:18080 image_name:1.
Crow Project compiled with g++ command and header only library in Docker container
I created the crow_all.h header only file from Crow Github repository and downloaded the asio package via VCPKG on my PC and copied the header files (C:\vcpkg\packages\asio_x64-windows\include) to my project folder into a subdirectory called asio. Hence, my project directory look like this:
project
|__asio
|__asio.hpp
|__asio
|__ ...
|__crow_all.h
|__Dockerfile
|__main.cpp
I build and run the Docker image/container with the same commands as above.
Dockerfile
(entire content from project directory gets copied into /usr/src/ directory in Docker container)
# get baseimage
FROM gcc:12
# copy files from local folder to destination
COPY . /usr/src
# define working directory in container
WORKDIR /usr/src
# compile main.cpp (-I/usr/src/asio/ link path starting from root)
RUN g++ -I/usr/src/asio/ main.cpp -lpthread -o app
# run executable
CMD [ "./app" ]
To the other questions
I still do not know, whether that is possible.
With such a (still) simple file structure no serious conflicts appeared.
|
73,332,656
| 73,332,713
|
How to fix a copy constructor that doesn't work?
|
I'm trying to simplify my code. Why I can't use the commented constructor instead of the previous (not commented) one?
struct Direction {
const double x, y, z;
Direction(double _X, double _Y, double _Z) : x(_X), y(_Y), z(_Z) {}
Direction(Direction& _D) : x(_D.x), y(_D.y), z(_D.z) {}
}
class Movement {
private:
const double v;
const Direction d;
public:
Movement(double _V, double _X, double _Y, double _Z) : v(_V), d(_X, _Y, _Z) {}
Movement(double _V, Direction _D) : v(_V), d(_D) {}
Movement(Movement& _M) : v(_M.v), d(_M.d.x, _M.d.y, _M.d.z) {} // this works
// Movement(Movement& _M) : v(_M.v), d(_M.d) {} // this doesn't work
}
Any ideas on how to make it work? Thank you.
|
The error message is rather clear:
<source>: In copy constructor 'Movement::Movement(Movement&)':
<source>:15:44: error: binding reference of type 'Direction&' to 'const Direction' discards qualifiers
15 | Movement(Movement& _M) : v(_M.v), d(_M.d) {} // this doesn't work
| ~~~^
<source>:4:26: note: initializing argument 1 of 'Direction::Direction(Direction&)'
4 | Direction(Direction& _D) : x(_D.x), y(_D.y), z(_D.z) {}
| ~~~~~~~~~~~^~
The member d is const, but the Direction constructor expects a non-const reference.
The code compiles if the constructor takes a constant referece, which it should, because the constructor does not modify the parameter:
struct Direction {
const double x, y, z;
Direction(double _X, double _Y, double _Z) : x(_X), y(_Y), z(_Z) {}
Direction(const Direction& _D) : x(_D.x), y(_D.y), z(_D.z) {}
};
class Movement {
private:
const double v;
const Direction d;
public:
Movement(double _V, double _X, double _Y, double _Z) : v(_V), d(_X, _Y, _Z) {}
Movement(double _V, Direction _D) : v(_V), d(_D) {}
//Movement(Movement& _M) : v(_M.v), d(_M.d.x, _M.d.y, _M.d.z) {} // this works
Movement(Movement& _M) : v(_M.v), d(_M.d) {} // this doesn't work
};
int main() {
Movement x(0.1,0.2,0.3,0.4);
Movement y(x);
}
However, const members are tricky and rarely the right way. The members are private, so there is no point in making them const even on a non-const Movement. The user has no way to modify them anyhow. I suggest to remove all const from members and add const to all reference arguments that can be const. Especially the copy constructor should take its parameter as const &.
struct Direction {
double x, y, z;
Direction(double _X, double _Y, double _Z) : x(_X), y(_Y), z(_Z) {}
Direction(const Direction& _D) : x(_D.x), y(_D.y), z(_D.z) {}
};
class Movement {
private:
double v;
Direction d;
public:
Movement(double _V, double _X, double _Y, double _Z) : v(_V), d(_X, _Y, _Z) {}
Movement(double _V, const Direction& _D) : v(_V), d(_D) {}
Movement(const Movement& _M) : v(_M.v), d(_M.d) {} // this doesn't work
};
int main() {
Movement x(0.1,0.2,0.3,0.4);
Movement y(x);
}
If Directions members should also not be modifiable after construction make them private. Making a class member private is sufficient to prevents its modification, while const members prevent a couple of useful operations (assignment etc).
|
73,332,890
| 73,333,022
|
Problem assigning integer a value from an array index
|
I am trying to create a function that takes a string as an input and extracts the first digit as an output. Here is the relevant code. I am new to coding so tips are appreciated.
int extractNum(string id){
int num=0;
bool found=false;
for(int i=0; i<id.length(); i++){
if(isdigit(id[i])){
num=id[i];
found=true;
if(found=true){
break;
}
}
}
return num;
};
The problem I am facing is when ever I pass a example string like "vr2498" it does take the '2' but on assigning the value to a variable or returning the value it changes to 50. Which is incorrect.
Summary: Need to extract first digit from a string.
|
Your restult num is an integer, but the "2" in your string is a character. When you assign num=id[i], you're converting the character "2" to its ASCII value, which is 50.
So, you need to convert that. The simplest way would be to just do num = id[i] - '0'. That works because in ASCII, numbers are consecutive with "0" being the first one.
The better solution here would be to use something like std::stoi which does that conversion. This would also allow converting more than one digit if that's what you want.
Also note you can just return from the loop directly, no need for break and found.
int extractNum(string id){
for(int i=0; i<id.length(); i++){
if(isdigit(id[i])){
//here, you could take more than one character
const auto digitString = id.substr(i, 1);
return std::stoi(digitString);
}
}
return 0;
};
|
73,332,899
| 73,333,082
|
use std::move twice when an argument is passed by value?
|
I need some feedback in order to see if I understand C++ move semantics correctly. Can someone tell me if the following example of using std::move - including the statements made in the comments - is correct? (No elaborate comments required if the answer is simply Yes)
#include <string>
#include <utility>
class MyClass
{
public:
void Set(std::string str)
{
myString = std::move(str);
}
private:
std::string myString;
};
int main()
{
std::string largeString = "A very long piece of text...";
// In the follwoing case largeString is copied once, because it is passed by value (correct?)
MyClass myClass;
myClass.Set(largeString);
// In the following case no copies of largeString are made, because it is moved twice (correct?)
MyClass myClass2;
myClass.Set(std::move(largeString)); // largeString can no longer be used in main() after this line
return 0;
}
|
You understood it correctly.
Also you can make your own class, log all constructors and check it by yourself.
|
73,332,909
| 73,333,009
|
Does resize on a std::vector<int> set the new elements to zero?
|
Consider
#include <vector>
int main()
{
std::vector<int> foo;
foo.resize(10);
// are the elements of foo zero?
}
Are the elements of foo all zero? I think they are from C++11 onwards. But would like to know for sure.
|
Are the elements of foo all zero?
Yes, this can be seen from std::vector::resize documentation which says:
If the current size is less than count,
additional default-inserted elements are appended
And from defaultInsertable:
By default, this will call placement-new, as by ::new((void*)p) T() (until C++20)std::construct_at(p) (since C++20) (that is, value-initialize the object pointed to by p). If value-initialization is undesirable, for example, if the object is of non-class type and zeroing out is not needed, it can be avoided by providing a custom Allocator::construct.
(emphasis mine)
Note the T() in the above quoted statement. This means that after the resize foo.resize(10);, elements of foo will contain value 0 as they were value initialized.
|
73,333,103
| 73,333,143
|
Assigning a new size to a dynamic array in a class - A question from a test
|
I'm trying to figure out why in this piece of code, every time the function f() is called, the function calls the destructor and does not reallocate the size of the array
I know if I change it to int f(A & a) { return 2 * a.n; }
it will work, but I still don't understand why it goes into the destructor.
class A {
public:
A(int i = 10) {
n = i;
p = new int[n];
for (int j = 0; j < n; j++) {
p[j] = 0;
}
}
~A() { delete p; }
int n;
int* p;
};
int f(A a) { return 2 * a.n; }
int main() {
A a1(5), a2(5);
cout << 1 << endl;
f(a1);
cout << 2 << endl;
f(a2);
cout << 3 << endl;
f(a1);
cout << 4 << endl;
f(a2);
}
|
Every time f(A a) returns, the parameter a used in the call is destroyed.
|
73,333,198
| 73,333,930
|
C++ best practice for overloading inherited class
|
Is this the proper (best) way to initialize both the constructor of the parent class (in this case an interface) and the constructor of the child class?
class Parent {
protected:
int x, y;
private:
int pvt = 2;
public:
int pub = 3;
Parent(int n1, int n2)
: x(n1), y(n2) {}
virtual void merge_parent() {
std::cout << "[parent]: " << x << y << pvt << pub << std::endl;
}
virtual void merge() = 0;
};
class Child : public Parent {
private:
int c;
public:
Child(int n1, int n2, int n3): Parent(n1, n2), c(n3) {}
void merge() override {
std::cout << "[child]: " << x << y << c << pub << std::endl;
}
};
int main() {
Child* p = new Child(1, 2, 3);
p->merge_parent();
p->merge();
}
|
Everything looks OK, EXCEPT you need to declare a virtual destructor in your base class.
class Parent {
public:
virtual ~Parent() = default;
};
If you do not do this the destructor in your derived class will not be called when attempting to delete a pointer of type Parent.
Parent* parent = new Child{1, 2, 3};
// The destructor in the derived class 'Child' will not be called
// unless you declare a virtual destructor in your base (Parent) class.
delete parent;
|
73,333,218
| 73,333,342
|
Strange effect with Nulltermination char inside of string
|
Simple Code example: Godbolt-Compiler Explorer
#include <cstdint>
#include <iostream>
using namespace std;
using u16 = uint16_t;
int main(){
//char str[] = "0123456789\0abcdefghijklmnopqrtsuvwxyz";
char str[] = "0123456789\00123456789\00123456789";
auto str_len = (sizeof(str)-1);
cout << "stringlength: " << str_len << "\n";
for(int ii=0; ii<str_len; ++ii){
cout << u16(str[ii]) << ",";
}
cout << "\n";
return 0;
}
Output is:
stringlength: 28
48,49,50,51,52,53,54,55,56,57,1,50,51,52,53,54,55,56,57,1,50,51,52,53,54,55,56,57,
which is the same array content as when viewed with a debugger...
Here Termchar, 0 and 1 replaced with a single char with value '1'
but when I change for the other definition of char str[] (the commented out one...)
I get 48,49,50,51,52,53,54,55,56,57,0,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,116,115,117,118,119,120,121,122,
which is correct.
So did I hit a strange unicode thing, or how to explain that effect?
PS: I use that char xyz[] definition, so (sizeof()-1) can be used as compile time strlen() calculation...
|
The easiest way to stop this from being interpreted as an octal escape sequence would be:
char str[] = "0123456789\0" "0123456789\0" "0123456789";
Or just use \000 as the null character:
char str[] = "0123456789\0000123456789\0000123456789";
|
73,333,832
| 73,333,924
|
initializing of a struct of whose members are array of another struct
|
I have
#include <iostream>
typedef struct coordinate{
double x;
double y;
}point;
typedef struct sc_cell{ // single cell
point sc[4];
}cell;
typedef struct sb_body { // for single body
point sb[4];
}body;
using namespace std;
int main()
{
body r_plate = {};
r_plate.sb[0] = { 0,0 };
r_plate.sb[1] = { 5,0 };
r_plate.sb[2] = { 5,1 };
r_plate.sb[3] = { 0,1 };
return 0;
}
Here, in main I have initialized the r_plate with 4 points and took 4 lines. is there any way to initialize it in a single line?
Something like r_plate = { { 0,0 },{ 5,0 },{ 5,1 },{ 0,1 } }(this shows error too many initializer values)
|
The structure body is an aggregate that contains data members that in turn are aggregates.
You need to write
body r_plate = { { { 0,0 },{ 5,0 },{ 5,1 },{ 0,1 } } };
That is the structure body contains an array so you have to write
body r_plate = { { ... } };
and each element of the array is an object of the structure type. So you will have
body r_plate = { { { 0,0 },{ 5,0 },{ 5,1 },{ 0,1 } } };
The following initializations will be less readable but correct
body r_plate = { { 0,0,5,0,5,1,0,1 } };
and
body r_plate = { 0,0,5,0,5,1,0,1 };
Here is a demonstration program.
#include <iostream>
typedef struct coordinate{
double x;
double y;
}point;
typedef struct sc_cell{ // single cell
point sc[4];
}cell;
typedef struct sb_body { // for single body
point sb[4];
}body;
using namespace std;
int main()
{
body r_plate = { 0,0,5,0,5,1,0,1 };
for ( const auto &p : r_plate.sb )
{
std::cout << "( " << p.x << ", " << p.y << " ) ";
}
std::cout << '\n';
r_plate = { { 0,0,5,0,5,1,0,1 } };
for ( const auto &p : r_plate.sb )
{
std::cout << "( " << p.x << ", " << p.y << " ) ";
}
std::cout << '\n';
r_plate = { { { 0,0 }, { 5,0 } , { 5,1 }, { 0,1 } } };
for ( const auto &p : r_plate.sb )
{
std::cout << "( " << p.x << ", " << p.y << " ) ";
}
std::cout << '\n';
return 0;
}
The program output is
( 0, 0 ) ( 5, 0 ) ( 5, 1 ) ( 0, 1 )
( 0, 0 ) ( 5, 0 ) ( 5, 1 ) ( 0, 1 )
( 0, 0 ) ( 5, 0 ) ( 5, 1 ) ( 0, 1 )
As for this assignment
r_plate = { { 0,0 },{ 5,0 },{ 5,1 },{ 0,1 } };
then the first inner brace is considered as starting point of the list-initialization of the array. As the structure has only one data member (the array) then all other list-initializations apart the first one do not have corresponding data members of the structure. So the compiler issues an error.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.