Search Results

Search found 2886 results on 116 pages for 'std'.

Page 8/116 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • C++ Program Always Crashes While doing a std::string assign

    - by bbazso
    I have been trying to debug a crash in my application that crashes (i.e. asserts a * glibc detected free(): invalid pointer: 0x000000000070f0c0 **) while I'm trying to do a simple assign to a string. Note that I'm compiling on a linux system with gcc 4.2.4 with an optimization level set to -O2. With -O0 the application no longer crashes. E.g. std::string abc; abc = "testString"; but if I changed the code as follows it no longer crashes std::string abc("testString"); So again I scratched my head! But the interesting pattern was that the crash moved later on in the application, AGAIN at another string. I found it weird that the application was continuously crashing on a string assign. A typical crash backtrace would look as follows: #0 0x00007f2c2663bfb5 in raise () from /lib64/libc.so.6 (gdb) bt #0 0x00007f2c2663bfb5 in raise () from /lib64/libc.so.6 #1 0x00007f2c2663dbc3 in abort () from /lib64/libc.so.6 #2 0x00000000004d8cb7 in people_streamingserver_sighandler (signum=6) at src/peoplestreamingserver.cpp:487 #3 <signal handler called> #4 0x00007f2c2663bfb5 in raise () from /lib64/libc.so.6 #5 0x00007f2c2663dbc3 in abort () from /lib64/libc.so.6 #6 0x00007f2c26680ce0 in ?? () from /lib64/libc.so.6 #7 0x00007f2c270ca7a0 in std::string::assign (this=0x7f2c21bc8d20, __str=<value optimized out>) at /home/bbazso/ThirdParty/sources/gcc-4.2.4/x86_64-pc-linux-gnu/libstdc++-v3/include/bits/basic_string.h:238 #8 0x00007f2c21bd874a in PEOPLESProtocol::GetStreamName (this=<value optimized out>, pRawPath=0x2342fd8 "rtmp://127.0.0.1/mp4:pop.mp4", lStreamName=@0x7f2c21bc8d20) at /opt/trx-HEAD/gcc/4.2.4/lib/gcc/x86_64-pc-linux-gnu/4.2.4/../../../../include/c++/4.2.4/bits/basic_string.h:491 #9 0x00007f2c21bd9daa in PEOPLESProtocol::SignalProtocolCreated (pProtocol=0x233a4e0, customParameters=@0x7f2c21bc8de0) at peoplestreamer/src/peoplesprotocol.cpp:240 This was really weird behavior and so I started to poke around further in my application to see if there was some sort of memory corruption (either heap or stack) error that could be occurring that could be causing this weird behavior. I even checked for ptr corruptions and came up empty handed. In addition to visual inspection of the code I also tried the following tools: Valgrind using both memcheck and exp-ptrcheck electric fence libsafe I compiled with -fstack-protector-all in gcc I tried MALLOC_CHECK_ set to 2 I ran my code through lint checks as well as cppcheck (to check for mistakes) And I stepped through the code using gdb So I tried a lot of stuff and still came up empty handed. So I was wondering if it could be something like a linker issue or a library issue of some sort that could be causing this problem. Are there any know issues with the std::string that make is susceptible to crashing in -O2 or maybe it has nothing to do with the optimization level? But the only pattern that I can see thus far in my problem is that it always seems to crash on a string and so I was wondering if anyone knew of any issues that my be causing this type of behavior. Thanks a lot!

    Read the article

  • $stdin compatibility with std::istream using swig, C++, and Ruby

    - by Kenny Peng
    I have a function in C++ that takes in an std::istream as the input: class Foo { Foo(std::istream &); } Using SWIG, I've bound it to Ruby, but Ruby's $stdin variable is fundamentally different from anything like the stream classes in C++, so I'm not sure how to either 1) expose the C++ class to Ruby in a way that I can use $stdin, or 2) convert $stdin into something the C++ class can understand. Anyone have experience with binding iostreams in C++ to Ruby? Thanks.

    Read the article

  • Java equivalent of C++ std::map?

    - by Rudiger
    I'm looking for a Java class with the characteristics of C++ std::map's usual implementation (as I understand it, a self-balancing binary search tree): O(log n) performance for insertion/removal/search Each element is composed of a unique key and a mapped value Keys follow a strict weak ordering I'm looking for implementations with open source or design documents; I'll probably end up rolling my own support for primitive keys/values. This question's style is similar to: Java equivalent of std::deque, whose answer was "ArrayDeque from Primitive Collections for Java".

    Read the article

  • [C++] std::string manipulation: whitespace, "newline escapes '\'" and comments #

    - by rubenvb
    Kind of looking for affirmation here. I have some hand-written code, which I'm not shy to say I'm proud of, which reads a file, removes leading whitespace, processes newline escapes '\' and removes comments starting with #. It also removes all empty lines (also whitespace-only ones). Any thoughts/recommendations? I could probably replace some std::cout's with std::runtime_errors... but that's not a priority here :) const int RecipeReader::readRecipe() { ifstream is_recipe(s_buffer.c_str()); if (!is_recipe) cout << "unable to open file" << endl; while (getline(is_recipe, s_buffer)) { // whitespace+comment removeLeadingWhitespace(s_buffer); processComment(s_buffer); // newline escapes + append all subsequent lines with '\' processNewlineEscapes(s_buffer, is_recipe); // store the real text line if (!s_buffer.empty()) v_s_recipe.push_back(s_buffer); s_buffer.clear(); } is_recipe.close(); return 0; } void RecipeReader::processNewlineEscapes(string &s_string, ifstream &is_stream) { string s_temp; size_t sz_index = s_string.find_first_of("\\"); while (sz_index <= s_string.length()) { if (getline(is_stream,s_temp)) { removeLeadingWhitespace(s_temp); processComment(s_temp); s_string = s_string.substr(0,sz_index-1) + " " + s_temp; } else cout << "Error: newline escape '\' found at EOF" << endl; sz_index = s_string.find_first_of("\\"); } } void RecipeReader::processComment(string &s_string) { size_t sz_index = s_string.find_first_of("#"); s_string = s_string.substr(0,sz_index); } void RecipeReader::removeLeadingWhitespace(string &s_string) { const size_t sz_length = s_string.size(); size_t sz_index = s_string.find_first_not_of(" \t"); if (sz_index <= sz_length) s_string = s_string.substr(sz_index); else if ((sz_index > sz_length) && (sz_length != 0)) // "empty" lines with only whitespace s_string.clear(); } Some extra info: the first s_buffer passed to the ifstream contains the filename, std::string s_buffer is a class data member, so is std::vector v_s_recipe. Any comment is welcome :)

    Read the article

  • passing a class method as opposed to a function in std::sort

    - by memC
    hi, Within a class, I am trying to sort a vector, by passing a method of the same class. But it gives errors at the time of compilation. Can anyone tell what the problem is? Thank you! it gives the following error: argument of type bool (Sorter::)(D&, D&)' does not matchbool (Sorter::*)(D&, D&)' I have also tried using sortBynumber(D const& d1, D const& d2) #include<vector> #include<stdio.h> #include<iostream> #include<algorithm> class D { public: int getNumber(); D(int val); ~D(){}; private: int num; }; D::D(int val){ num = val; }; int D::getNumber(){ return num; }; class Sorter { public: void doSorting(); bool sortByNumber(D& d1, D& d2); std::vector<D> vec_D; Sorter(); ~Sorter(){}; private: int num; }; Sorter::Sorter(){ int i; for ( i = 0; i < 10; i++){ vec_D.push_back(D(i)); } }; bool Sorter::sortByNumber(D& d1, D& d2){ return d1.getNumber() < d2.getNumber(); }; void Sorter::doSorting(){ std::sort(vec_D.begin(), vec_D.end(), this->sortByNumber); }; int main(){ Sorter s; s.doSorting(); std::cout << "\nPress RETURN to continue..."; std::cin.get(); return 0; }

    Read the article

  • [C++] std::tring manipulation: whitespace, "newline escapes '\'" and comments #

    - by rubenvb
    Kind of looking for affirmation here. I have some hand-written code, which I'm not shy to say I'm proud of, which reads a file, removes leading whitespace, processes newline escapes '\' and removes comments starting with #. It also removes all empty lines (also whitespace-only ones). Any thoughts/recommendations? I could probably replace some std::cout's with std::runtime_errors... but that's not a priority here :) const int RecipeReader::readRecipe() { ifstream is_recipe(s_buffer.c_str()); if (!is_recipe) cout << "unable to open file" << endl; while (getline(is_recipe, s_buffer)) { // whitespace+comment removeLeadingWhitespace(s_buffer); processComment(s_buffer); // newline escapes + append all subsequent lines with '\' processNewlineEscapes(s_buffer, is_recipe); // store the real text line if (!s_buffer.empty()) v_s_recipe.push_back(s_buffer); s_buffer.clear(); } is_recipe.close(); return 0; } void RecipeReader::processNewlineEscapes(string &s_string, ifstream &is_stream) { string s_temp; size_t sz_index = s_string.find_first_of("\\"); while (sz_index <= s_string.length()) { if (getline(is_stream,s_temp)) { removeLeadingWhitespace(s_temp); processComment(s_temp); s_string = s_string.substr(0,sz_index-1) + " " + s_temp; } else cout << "Error: newline escape '\' found at EOF" << endl; sz_index = s_string.find_first_of("\\"); } } void RecipeReader::processComment(string &s_string) { size_t sz_index = s_string.find_first_of("#"); s_string = s_string.substr(0,sz_index); } void RecipeReader::removeLeadingWhitespace(string &s_string) { const size_t sz_length = s_string.size(); size_t sz_index = s_string.find_first_not_of(" \t"); if (sz_index <= sz_length) s_string = s_string.substr(sz_index); else if ((sz_index > sz_length) && (sz_length != 0)) // "empty" lines with only whitespace s_string.clear(); } Some extra info: std::string s_buffer is a class data member, so is std::vector v_s_recipe. Any comment is welcome :)

    Read the article

  • Sort std::vector by an element inside?

    - by user146780
    I currently have a std::vector which holds std::vector of double. I'd want to sort it by the second element of the double vectore. ex: instead of sorting by MyVec[0] or myvec[1] I wat it to sort myVec[0] and myvec[1] based on myvec[0][1] myvec[1][1]. Basically sort by a contained value, not the objects in it. so if myvec[0][1] is less than myvec[1][1] then myvec[0] and myvec[1] will swap. Thanks

    Read the article

  • Get last/newly added element in std::set

    - by Dave17
    can you get the last or newly added element in std::set? for example say if the loop runs to collect the elements to fill in the std::set. if on the first run the set was, [0] "A" [1] "B" [2] "D" and, on second run, the set becomes [0] "A" [1] "B" [2] "C" [3] "D" How would you check if 'C' is the new element that was added?

    Read the article

  • Access element of pointed std::vector

    - by user146780
    I have a function where I provide a pointer to a std::vector. I want to make x = to vector[element] but i'm getting compiler errors. I'm doing: void Function(std::vector<int> *input) { int a; a = *input[0]; } What is the right way to do this? Thanks

    Read the article

  • Creating Binary Block from struct

    - by MOnsDaR
    I hope the title is describing the problem, i'll change it if anyone has a better idea. I'm storing information in a struct like this: struct AnyStruct { AnyStruct : testInt(20), testDouble(100.01), testBool1(true), testBool2(false), testBool3(true), testChar('x') {} int testInt; double testDouble; bool testBool1; bool testBool2; bool testBool3; char testChar; std::vector<char> getBinaryBlock() { //how to build that? } } The struct should be sent via network in a binary byte-buffer with the following structure: Bit 00- 31: testInt Bit 32- 61: testDouble most significant portion Bit 62- 93: testDouble least significant portion Bit 94: testBool1 Bit 95: testBool2 Bit 96: testBool3 Bit 97-104: testChar According to this definition the resulting std::vector should have a size of 13 bytes (char == byte) My question now is how I can form such a packet out of the different datatypes I've got. I've already read through a lot of pages and found datatypes like std::bitset or boost::dynamic_bitset, but neither seems to solve my problem. I think it is easy to see, that the above code is just an example, the original standard is far more complex and contains more different datatypes. Solving the above example should solve my problems with the complex structures too i think. One last point: The problem should be solved just by using standard, portable language-features of C++ like STL or Boost (

    Read the article

  • How to achieve to following C++ output formatting?

    - by Yan Cheng CHEOK
    I wish to print out double as the following rules : 1) No scietific notation 2) Maximum decimal point is 3 3) No trailing 0. For example : 0.01 formated to "0.01" 2.123411 formatted to "2.123" 2.11 formatted to "2.11" 2.1 formatted to "2.1" 0 formatted to "0" By using .precision(3) and std::fixed, I can only achieve rule 1) and rule 2), but not rule 3) 0.01 formated to "0.010" 2.123411 formatted to "2.123" 2.11 formatted to "2.110" 2.1 formatted to "2.100" 0 formatted to "0" Code example is as bellow : #include <iostream> int main() { std::cout.precision(3); std::cout << std::fixed << 0.01 << std::endl; std::cout << std::fixed << 2.123411 << std::endl; std::cout << std::fixed << 2.11 << std::endl; std::cout << std::fixed << 2.1 << std::endl; std::cout << std::fixed << 0 << std::endl; getchar(); } any idea?

    Read the article

  • unformatted input to a std::string instead of c-string from binary file.

    - by posop
    ok i have this program working using c-strings. I am wondering if it is possible to read in blocks of unformatted text to a std::string? I toyed arround with if >> but this reads in line by line. I've been breaking my code and banging my head against the wall trying to use std::string, so I thought it was time to enlist the experts. Here's a working program you need to supply a file "a.txt" with some content to make it run. i tried to fool around with: in.read (const_cast<char *>(memblock.c_str()), read_size); but it was acting odd. I had to do std::cout << memblock.c_str() to get it to print. and memblock.clear() did not clear out the string. anyway, if you can think of a way to use STL I would greatly appreciate it. Here's my program using c-strings // What this program does now: copies a file to a new location byte by byte // What this program is going to do: get small blocks of a file and encrypt them #include <fstream> #include <iostream> #include <string> int main (int argc, char * argv[]) { int read_size = 16; int infile_size; std::ifstream in; std::ofstream out; char * memblock; int completed = 0; memblock = new char [read_size]; in.open ("a.txt", std::ios::in | std::ios::binary | std::ios::ate); if (in.is_open()) infile_size = in.tellg(); out.open("b.txt", std::ios::out | std::ios::trunc | std::ios::binary); in.seekg (0, std::ios::beg);// get to beginning of file while(!in.eof()) { completed = completed + read_size; if(completed < infile_size) { in.read (memblock, read_size); out.write (memblock, read_size); } // end if else // last run { delete[] memblock; memblock = new char [infile_size % read_size]; in.read (memblock, infile_size % read_size + 1); out.write (memblock, infile_size % read_size ); } // end else } // end while } // main if you see anything that would make this code better please feel free to let me know.

    Read the article

  • Confused about C++'s std::wstring, UTF-16, UTF-8 and displaying strings in a windows GUI

    - by dfrey
    I'm working on a english only C++ program for Windows where we were told "always use std::wstring", but it seems like nobody on the team really has much of an understanding beyond that. I already read the question titled "std::wstring VS std::string. It was very helpful, but I still don't quite understand how to apply all of that information to my problem. The program I'm working on displays data in a Windows GUI. That data is persisted as XML. We often transform that XML using XSLT into HTML or XSL:FO for reporting purposes. My feeling based on what I have read is that the HTML should be encoded as UTF-8. I know very little about GUI development, but the little bit I have read indicates that the GUI stuff is all based on UTF-16 encoded strings. I'm trying to understand where this leaves me. Say we decide that all of our persisted data should be UTF-8 encoded XML. Does this mean that in order to display persisted data in a UI component, I should really be performing some sort of explicit UTF-8 to UTF-16 transcoding process? I suspect my explanation could use clarification, so I'll try to provide that if you have any questions.

    Read the article

  • std::locale breakage on MacOS 10.6 with LANG=en_US.UTF-8

    - by fixermark
    I have a C++ application that I am porting to MacOSX (specifically, 10.6). The app makes heavy use of the C++ standard library and boost. I recently observed some breakage in the app that I'm having difficulty understanding. Basically, the boost filesystem library throws a runtime exception when the program runs. With a bit of debugging and googling, I've reduced the offending call to the following minimal program: #include <locale> int main ( int argc, char *argv [] ) { std::locale::global(std::locale("")); return 0; } This program fails when I run this through g++ and execute the resulting program in an environment where LANG=en_US.UTF-8 is set (which on my computer is part of the default bash session when I create a new console window). Clearing the environment variable (setenv LANG=) allows the program to run without issues. But I'm surprised I'm seeing this breakage in the default configuration. My questions are: Is this expected behavior for this code on MacOS 10.6? What would a proper workaround be? I can't really re-write the function because the version of the boost libraries we are using executes this statement internally as part of the filesystem library. For completeness, I should point out that the program from which this code was synthesized crashes when launched via the 'open' command (or from the Finder) but not when Xcode runs the program in Debug mode. edit The error given by the above code on 10.6.1 is: $ ./locale terminate called after throwing an instance of 'std::runtime_error' what(): locale::facet::_S_create_c_locale name not valid Abort trap

    Read the article

  • FileSystemWatcher does not fire when using C++ std::ofstream

    - by Adam Haile
    I'm trying to add a log monitor to an in-house test utility for a windows service I'm working on. The service is written in C++ (win32) and the utility is in .NET (C#) The log monitor works for many other C++ apps I've written, but not for my service. The only main difference I can see is that the other apps use the older ::WriteFile() to output to the log, whereas in the service I'm using std::ofstream like this: std::ofstream logFile; logFile.open("C:\\mylog.log"); logFile << "Hello World!" << std::endl; logFile.flush(); From my utility I use FileSystemWatcher like this: FileSystemWatcher fsw = new FileSystemWatcher(@"C:\", "mylog.log"); fsw.Changed += new FileSystemEventHandler(fsw_Handler); fsw.EnableRaisingEvents = true; But for the service, it never gets any change events as the log is updated. I've found that any example code using FileSystemWatcher I've come across online has the same exact issue as well... But, I know the events should be available because other log monitor apps (like BareTail) work fine with the service log file. I'd rather get the C# code for the utility to just work so it works with anything, but if I have to change the logging code for the service I will. Does anyone see what's going wrong here?

    Read the article

  • Free Memory Occupied by Std List, Vector, Map etc

    - by Graviton
    Coming from a C# background, I have only vaguest idea on memory management on C++-- all I know is that I would have to free the memory manually. As a result my C++ code is written in such a way that objects of the type std::vector, std::list, std::map are freely instantiated, used, but not freed. I didn't realize this point until I am almost done with my programs, now my code is consisted of the following kinds of patterns: struct Point_2 { double x; double y; }; struct Point_3 { double x; double y; double z; }; list<list<Point_2>> Computation::ComputationJob(list<Point_3> pts3D, vector<Point_2> vectors) { map<Point_2, double> pt2DMap=ConstructPointMap(pts3D); vector<Point_2> vectorList = ConstructVectors(vectors); list<list<Point_2>> faceList2D=ConstructPoints(vectorList , pt2DMap); return faceList2D; } My question is, must I free every.single.one of the list usage ( in the above example, this means that I would have to free pt2DMap, vectorList and faceList2D)? That would be very tedious! I might just as well rewrite my Computation class so that it is less prone to memory leak. Any idea how to fix this?

    Read the article

  • Coordinating typedefs and structs in std::multiset (C++)

    - by Sarah
    I'm not a professional programmer, so please don't hesitate to state the obvious. My goal is to use a std::multiset container (typedef EventMultiSet) called currentEvents to organize a list of structs, of type Event, and to have members of class Host occasionally add new Event structs to currentEvents. The structs are supposed to be sorted by one of their members, time. I am not sure how much of what I am trying to do is legal; the g++ compiler reports (in "Host.h") "error: 'EventMultiSet' has not been declared." Here's what I'm doing: // Event.h struct Event { public: bool operator < ( const Event & rhs ) const { return ( time < rhs.time ); } double time; int eventID; int hostID; }; // Host.h ... void calcLifeHist( double, EventMultiSet * ); // produces compiler error ... void addEvent( double, int, int, EventMultiSet * ); // produces compiler error // Host.cpp #include "Event.h" ... // main.cpp #include "Event.h" ... typedef std::multiset< Event, std::less< Event > > EventMultiSet; EventMultiSet currentEvents; EventMultiSet * cePtr = &currentEvents; ... Major questions Where should I include the EventMultiSet typedef? Are my EventMultiSet pointers obviously problematic? Is the compare function within my Event struct (in theory) okay? Thank you very much in advance.

    Read the article

  • const pod and std::vector

    - by Baz
    To get this code to compile: std::vector<Foo> factory() { std::vector<Foo> data; return data; } I have to define my POD like this: struct Foo { const int i; const int j; Foo(const int _i, const int _j): i(_i), j(_j) {} Foo(Foo& foo): i(foo.i), j(foo.j){} Foo operator=(Foo& foo) { Foo f(foo.i, foo.j); return f; } }; Is this the correct approach for defining a pod where I'm not interested in changing the pod members after creation? Why am I forced to define a copy constructor and overload the assignment operator? Is this compatible for different platform implementations of std::vector? Is it wrong in your opinion to have const PODS like this? Should I just leave them as non-const?

    Read the article

  • Unresolved External Symbol? error lnk2019

    - by jay
    Hello, I was wondering if anyone knew what this error meant. Thanks error LNK2019: unresolved external symbol "public: void __thiscall LinkedList,class std::allocator ::LocItem *::decreasekey(class PriorityList,class std::allocator ::LocItem * const &)" (?decreasekey@?$LinkedList@HPAVLocItem@?$PriorityList@HV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@@@@QAEXABQAVLocItem@?$PriorityList@HV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@@@Z) referenced in function "public: void __thiscall PriorityList,class std::allocator ::decreasekey(class PriorityList,class std::allocator ::Locator)" (?decreasekey@?$PriorityList@HV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@@QAEXVLocator@1@@Z)

    Read the article

  • C++ string sort like a human being?

    - by Walter Nissen
    I would like to sort alphanumeric strings the way a human being would sort them. I.e., "A2" comes before "A10", and "a" certainly comes before "Z"! Is there any way to do with without writing a mini-parser? Ideally it would also put "A1B1" before "A1B10". I see the question "Natural (human alpha-numeric) sort in Microsoft SQL 2005" with a possible answer, but it uses various library functions, as does "Sorting Strings for Humans with IComparer". Below is a test case that currently fails: #include <set> #include <iterator> #include <iostream> #include <vector> #include <cassert> template <typename T> struct LexicographicSort { inline bool operator() (const T& lhs, const T& rhs) const{ std::ostringstream s1,s2; s1 << toLower(lhs); s2 << toLower(rhs); bool less = s1.str() < s2.str(); std::cout<<s1.str()<<" "<<s2.str()<<" "<<less<<"\n"; return less; } inline std::string toLower(const std::string& str) const { std::string newString(""); for (std::string::const_iterator charIt = str.begin(); charIt!=str.end();++charIt) { newString.push_back(std::tolower(*charIt)); } return newString; } }; int main(void) { const std::string reference[5] = {"ab","B","c1","c2","c10"}; std::vector<std::string> referenceStrings(&(reference[0]), &(reference[5])); //Insert in reverse order so we know they get sorted std::set<std::string,LexicographicSort<std::string> > strings(referenceStrings.rbegin(), referenceStrings.rend()); std::cout<<"Items:\n"; std::copy(strings.begin(), strings.end(), std::ostream_iterator<std::string>(std::cout, "\n")); std::vector<std::string> sortedStrings(strings.begin(), strings.end()); assert(sortedStrings == referenceStrings); }

    Read the article

  • Simplifying C++11 optimal parameter passing when a copy is needed

    - by Mr.C64
    It seems to me that in C++11 lots of attention was made to simplify returning values from functions and methods, i.e.: with move semantics it's possible to simply return heavy-to-copy but cheap-to-move values (while in C++98/03 the general guideline was to use output parameters via non-const references or pointers), e.g.: // C++11 style vector<string> MakeAVeryBigStringList(); // C++98/03 style void MakeAVeryBigStringList(vector<string>& result); On the other side, it seems to me that more work should be done on input parameter passing, in particular when a copy of an input parameter is needed, e.g. in constructors and setters. My understanding is that the best technique in this case is to use templates and std::forward<>, e.g. (following the pattern of this answer on C++11 optimal parameter passing): class Person { std::string m_name; public: template <class T, class = typename std::enable_if < std::is_constructible<std::string, T>::value >::type> explicit Person(T&& name) : m_name(std::forward<T>(name)) { } ... }; A similar code could be written for setters. Frankly, this code seems boilerplate and complex, and doesn't scale up well when there are more parameters (e.g. if a surname attribute is added to the above class). Would it be possible to add a new feature to C++11 to simplify code like this (just like lambdas simplify C++98/03 code with functors in several cases)? I was thinking of a syntax with some special character, like @ (since introducing a &&& in addition to && would be too much typing :) e.g.: class Person { std::string m_name; public: /* Simplified syntax to produce boilerplate code like this: template <class T, class = typename std::enable_if < std::is_constructible<std::string, T>::value >::type> */ explicit Person(std::string@ name) : m_name(name) // implicit std::forward as well { } ... }; This would be very convenient also for more complex cases involving more parameters, e.g. Person(std::string@ name, std::string@ surname) : m_name(name), m_surname(surname) { } Would it be possible to add a simplified convenient syntax like this in C++? What would be the downsides of such a syntax?

    Read the article

  • Using numeric_limits::max() in constant expressions

    - by FireAphis
    Hello, I would like to define inside a class a constant which value is the maximum possible int. Something like this: class A { ... static const int ERROR_VALUE = std::numeric_limits<int>::max(); ... } This declaration fails to compile with the following message: numeric.cpp:8: error: 'std::numeric_limits::max()' cannot appear in a constant-expression numeric.cpp:8: error: a function call cannot appear in a constant-expression I understand why this doesn't work, but two things look weird to me: It seems to me a natural decision to use the value in constant expressions. Why did the language designers decide to make max() a function thus not allowing this usage? The spec claims in 18.2.1 that For all members declared static const in the numeric_limits template, specializations shall define these values in such a way that they are usable as integral constant expressions. Doesn't it mean that I should be able to use it in my scenario and doesn't it contradict the error message? Thank you.

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >