Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
evensevenone
May 12, 2001
Glass is a solid.
is the EOF marker in the input file on it's own line?

Adbot
ADBOT LOVES YOU

That Turkey Story
Mar 30, 2003

rufius posted:

I've been working with C++ for a while now and have a good grasp on just about every area *except* templates.

That's a really big gap, to say the least :p

As you mentioned, C++ Templates: The Complete Guide is good, you should also take a look at C++ Template Metaprogramming. If you really want a foundation in Generic Programming, which you do if you want to really "get" libraries such as the STL or wish to go into library development on your own, read Elements of Programming.

rufius posted:

My primary questions are:
1) Will buying Vandervoorde's book (mentioned above) suffice for me figuring out the STL style of programming? I want to learn more about using the STL (and/or Boost). I don't need a whole lot of hand-holding, more like principles for understanding why X is done a particular way in the STL.

If you want to understand Generic Programming and the rationale behind design decisions like those in the STL, again, get Elements of Programming. There just literally aren't any other books specifically on the paradigm. If you only get one book, make it that one -- it's not going to teach you C++-specific "tricks" as it's not really a C++ book, but you'll come out with a better understanding of modern C++ designs.

rufius posted:

2) Is Vandervoorde's the best reference for templates?

It's definitely up there, but if you want to be on the bleeding-edge of all the amazing things you can do with templates you should just follow Boost development. Books simply can't keep up. Read the Boost docs, follow the dev mailing list, and in no particular order explore Boost.MPL, Boost.Proto, Boost.Spirit, Boost.Phoenix, the Boost Multi-index Containers Library, enable_if, Boost.Type_Traits, Boost.GIL, the Boost Graph Library, Boost.Operators, Boost.Parameter, Boost.Fusion, and Boost.Variant. Each of those libraries makes heavy use of modern template techniques and/or is a great example of Generic Programming. There's also a growing number of people on these forums who have a solid understanding of templates so if you have something specific to ask you'll probably get an answer here pretty quickly.

HFX
Nov 29, 2004

MrMoo posted:

Ahh, Linux. Try __FD_SETSIZE instead, on Solaris FD_SETSIZE works fine as I have it in production in a few banks.

http://www.issociate.de/board/post/504324/FD_SETSIZE_with_large_

__FD_SET_SIZE didn't work either. I replaced select and the associated functions in the library I'm using with epoll. This seems to have solved the Segmentation fault issue. Sadly, wanting to do it fastest and with minimal changes, there is a lot of loops left behind int eh code that don't really need to be there. I'd redo the architecture and keep the interface the same for the clients, but I haven't convinced management that the time is worth it when other issues have arisen. I swat one bug, 2 others pop up (masked by the previous).

A MIRACLE
Sep 17, 2007

All right. It's Saturday night; I have no date, a two-liter bottle of Shasta and my all-Rush mix-tape... Let's rock.

evensevenone posted:

is the EOF marker in the input file on it's own line?

Should I do something like
code:
while ( in.getline(inputline, 256) && !in.EOF() ) { ...

SaTaMaS
Apr 18, 2003
I'm trying to assign a struct to a map, but I keep getting the error "expected an expression"

struct tier {
int index;
char option[];
};
...

tier test = {1,{'G','Y','R'}};//works fine!
map<string, tier> pavLeader1Map;
pavLeader1Map["menu90"] = {1,{'G','Y','R'}};//give an error


Do I need to do some kind of casting?

UraniumAnchor
May 21, 2006

Not a walrus.
That particular syntax only works on the same line as a struct declaration, hence why the first one works and the second does not. The second one is an assignment, not a declaration, so you have to use an actual variable.

Edit: This variable can be a temporary if you provide a constructor:

code:
struct Foo{
  int x;
  float y;
  Foo(int x, float y) : x(x), y(y) {}
};

void somefunc() {
...
   map<int, Foo> m;
...
   m[5] = Foo(10, 20.0f);
...
};

UraniumAnchor fucked around with this message at 21:20 on Apr 7, 2011

Edison was a dick
Apr 3, 2010

direct current :roboluv: only
I don't know how standard it is, but C with gcc you can assign to a structure by
code:
struct tier test;
test = (struct tier){1, {'G', 'Y', 'R'}};
You're probably better off with the constructor solution.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
Note that that won't actually copy the flex-array members, which have not had memory allocated for them by the original variable. In general, flex-array members can only be established by the original declaration. Also, do you *really* need to be using flex-array members?

That Turkey Story
Mar 30, 2003

rjmccall posted:

Note that that won't actually copy the flex-array members, which have not had memory allocated for them by the original variable. In general, flex-array members can only be established by the original declaration. Also, do you *really* need to be using flex-array members?

Are flex-arrays even in 0x? I thought they were just a C thing that didn't get brought over.

Johnson
Feb 22, 2011

by Fistgrrl
Noob question here:
I'm trying to learn C++. I downloaded Dev-C++ and wrote the "hello world" program, but when I run it, the command promp opens and closes immediately.
I googled about this, and people mentioned writing "cin.gate()" at the end, but that hasn't helped me at all.
How do I stop it from closing my files when I run them?

nielsm
Jun 1, 2009



Johnson posted:

Noob question here:
I'm trying to learn C++. I downloaded Dev-C++ and wrote the "hello world" program, but when I run it, the command promp opens and closes immediately.
I googled about this, and people mentioned writing "cin.gate()" at the end, but that hasn't helped me at all.
How do I stop it from closing my files when I run them?

You're creating a console mode application, so Windows creates a console window your program's output is displayed in, but that window closes as soon as your program ends.

A bunch of things you can do if you want the window to stay up:
- Make the program wait, either just for a period of time, or until you do something like press a key.
- Run the program from an already existing console window, i.e. start cmd and run your compiled program from there.
- A kind of combination of the two, write a batch file that runs your program and then waits afterwards.

I'd strongly recommend one of the two latter, although the first also has its uses.
Mainly, if you aren't comfortable with using a command line, it's a good idea to become so. This looks like a decent guide. (Also it's worth noting that Windows' command line is not DOS. DOS is a 16 bit operating system and last time you ran DOS was with Windows 98.)
When you have a working understanding of the command line, you can also write simple batch files, just files with extension .cmd or .bat that contain a list of commands. That could be e.g. be the name of your compiled program, followed by the pause command on the next line.

If you want to make your program itself wait instead, read on.
First, why it's a bad idea: If you're writing a non-interactive program, i.e. one that just does a prescribed job without taking user input, it's silly to add a delay: You're just making the program take longer to complete without any gain. If you wanted to time to read its output you could be calling it from a batch file and pause after its execution, or you could redirect the output to a file, or several other things.
Now, what you'd do to make the program wait: The simplest is to just read something, anything, from standard input, i.e. std::cin when using C++'s iostreams. You could do that like this:
char dummy; std::cin >> dummy;
In the context of iostreams, the >> operator is used as "take from", the same way as << is used as "put to". (The general meaning of those operators is something entirely different, they're the bit-shifting operators in C. Important to remember!)
What this will do is read a single character from standard input, but you'll notice it only actually continues after you press Enter to finish a line, that's because of line buffering: The input system by default tries to read an entire line before passing anything to the program. There's also ways to do unbuffered input, but I can't remember them right now and can't bother looking it up.

Lastly, you could of course begin writing GUI programs ;)

That Turkey Story
Mar 30, 2003

nielsm posted:

:words:

Or you could just do cin.ignore()

Optimus Prime Ribs
Jul 25, 2007

nielsm posted:

Lastly, you could of course begin writing GUI programs ;)

Even if this was tongue-in-cheek it's pretty bad advice for someone just starting to learn the language.

nielsm
Jun 1, 2009



Optimus Prime Ribs posted:

Even if this was tongue-in-cheek it's pretty bad advice for someone just starting to learn the language.

Yes, seriously: Don't attempt to write GUI programs before you have a good grasp of the language basics and can structure your code well. GUI systems are crazy complex.

(Also on that topic, systems that give you graphical GUI designers with loads of auto-generated code are pretty bad for learning. You easily end up picking up lots of bad habits on code structure, and might never properly advance from that stage.)

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

That Turkey Story posted:

Are flex-arrays even in 0x? I thought they were just a C thing that didn't get brought over.

Oh, yes, they're also definitely not a C++ thing, even if GCC doesn't explicitly break them.

Joda
Apr 24, 2010

When I'm off, I just like to really let go and have fun, y'know?

Fun Shoe
I'm currently reading Beginning C++ through Game Programming and am almost done, so I wanted to ask here what would be a logical next step? I should mention I prefer books, simply because I find them easier to read and they're generally more mobile.

I might decide to write a couple of text based applications before I move on to further cement the stuff I've learnt from the book, but I'd like to have a new book lying around for when I feel ready to move on.

I was thinking I'd move on with a book on a GUI or Windows API, or maybe APIs in general, or is that too advanced? If it is too advanced, are there any books that cover that middle-ground?

It should be mentioned that I have no prior experience with programming before starting to read this book.

Thanks.

EDIT: Fixed the book title.

Joda fucked around with this message at 14:26 on Apr 8, 2011

nielsm
Jun 1, 2009



Joda posted:

I'm currently reading Beginning C++ through Game Programming and am almost done, so I wanted to ask here what would be a logical next step? I should mention I prefer books, simply because I find them easier to read and they're generally more mobile.

It should be mentioned that I have no prior experience with programming before starting to read this book.

Write a load of programs. Maybe learn a simple library for doing fancier-than-iostreams text interfaces, something like Ncurses if you can find a version that works for you.

While doing that, learn a second language. I'd recommend Python, it's similar enough that you can transfer some knowledge and not start entirely blank, but different enough that you'll be forced to think and re-organise what you've learned so far, making you a better programmer overall.

Then begin thinking about real GUI.

Can't help with books.

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!

Joda posted:

I was thinking I'd move on with a book on a GUI or Windows API, or maybe APIs in general, or is that too advanced? If it is too advanced, are there any books that cover that middle-ground?
The Windows API is probably not too advanced. It's a lot of unintuitive stuff, so it can seem overwhelming at first, but basically the ancient documentation for "message loop", "winmain" and either "wndproc" or "windowproc" (I forget) is enough to get you a working program.

I recommend not trying to use the MFC because it's loving hideous.

Joda
Apr 24, 2010

When I'm off, I just like to really let go and have fun, y'know?

Fun Shoe

nielsm posted:

Write a load of programs. Maybe learn a simple library for doing fancier-than-iostreams text interfaces, something like Ncurses if you can find a version that works for you.

While doing that, learn a second language. I'd recommend Python, it's similar enough that you can transfer some knowledge and not start entirely blank, but different enough that you'll be forced to think and re-organise what you've learned so far, making you a better programmer overall.

Then begin thinking about real GUI.

Can't help with books.

Thanks. I did a quick search on Amazon and found this, which I might pick up when I feel secure enough in C++.

In the meantime; are there any libraries that come with the standard libraries of either g++ or MS Visual Studio 2010, that allow a beginner such as myself to do basic stuff such as clear the console before reprinting output, maybe add colour or something like that to the text and write/read from separate files on the hard-drive? I don't expect there to be any books on something that narrow and outdated, but I'd settle for an online tutorial just to get a grip of the objects and functions.

Joda fucked around with this message at 16:20 on Apr 8, 2011

rufius
Feb 27, 2011

Clear alcohols are for rich women on diets.

That Turkey Story posted:

That's a really big gap, to say the least :p

As you mentioned, C++ Templates: The Complete Guide is good, you should also take a look at C++ Template Metaprogramming. If you really want a foundation in Generic Programming, which you do if you want to really "get" libraries such as the STL or wish to go into library development on your own, read Elements of Programming.


If you want to understand Generic Programming and the rationale behind design decisions like those in the STL, again, get Elements of Programming. There just literally aren't any other books specifically on the paradigm. If you only get one book, make it that one -- it's not going to teach you C++-specific "tricks" as it's not really a C++ book, but you'll come out with a better understanding of modern C++ designs.


It's definitely up there, but if you want to be on the bleeding-edge of all the amazing things you can do with templates you should just follow Boost development. Books simply can't keep up. Read the Boost docs, follow the dev mailing list, and in no particular order explore Boost.MPL, Boost.Proto, Boost.Spirit, Boost.Phoenix, the Boost Multi-index Containers Library, enable_if, Boost.Type_Traits, Boost.GIL, the Boost Graph Library, Boost.Operators, Boost.Parameter, Boost.Fusion, and Boost.Variant. Each of those libraries makes heavy use of modern template techniques and/or is a great example of Generic Programming. There's also a growing number of people on these forums who have a solid understanding of templates so if you have something specific to ask you'll probably get an answer here pretty quickly.

That works out well actually, I'd forgotten I owned that book (Elements of Programming). My undergrad thesis adviser gave me the book as a graduation present but I never got around to reading it (about a year ago). I seem to recall him saying something to the effect of "there will come a time when you'll need to read this."

I will look into Boost though and read the book. Thanks for the advice, looks like I don't need to buy any books :toot:.

nielsm
Jun 1, 2009



Joda posted:

In the meantime; are there any libraries that come with the standard libraries of either g++ or MS Visual Studio 2010, that allow a beginner such as myself to do basic stuff such as clear the console before reprinting output, maybe add colour or something like that to the text
If you don't mind writing Windows-specific code, you can call the Windows console functions directly.

Joda posted:

and write/read from separate files on the hard-drive?

The C++ standard library already provides functions for that, and it's barely any different from going to the console.
code:
#include <iostream>
#include <fstream>
int main() {
  // declare a file output stream variable
  // creates an output file stream object
  std::ofstream file;
  // call the open function on the ofstream, to open a file for writing
  file.open("somefile.txt");
  // write something to the file
  file << "Hello file-writing world." << std::endl;
  // get a number from the user on the console
  int number;
  std::cout << "Enter a number: ";
  std::cin >> number;
  // write it to the file
  file << "The user entered the number " << number << " for this file." << std::endl;
  std::cout << "Your file has been written. Have a good day!" << std::endl;
  // always close your files after use!
  file.close()
}

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!

nielsm posted:

If you don't mind writing Windows-specific code, you can call the Windows console functions directly.
Or you can just output ANSI escape codes as [part of] your strings, which can do all the things requested and is compatible with most systems including remote connections.

Edit: except not Windows consoles apparently, just tested with Perl. Doh. Unless you set "ANSI.SYS" as the device.
In which case your best bet if you want to go cross-platform at all is to use a Curses library - pdcurses for Windows and ncurses for all the POSIX-compatibles.

roomforthetuna fucked around with this message at 20:01 on Apr 8, 2011

Joda
Apr 24, 2010

When I'm off, I just like to really let go and have fun, y'know?

Fun Shoe
Great! Thanks for the help.

I tried looking at the link you posted nielsm, but it all seems pretty daunting to me, and ANSI escape codes seem a lot simpler. I do most coding on my laptop which has Ubuntu and g++, so Windows incompatibility shouldn't pose a major problem.

Just to make sure I understood it right; this should end up as a blank console, right?

code:
#include <iostream>

int main()
{
  std::cout << "Something!\[2J";

  return 0;
}
That's what I could gather from cross checking that table with a quick google search at least, but I might not've understood it right.

EDIT: Corrected code and understood why it's a good idea to get more used to the language before moving on :downs:

Joda fucked around with this message at 20:30 on Apr 8, 2011

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!

Joda posted:

cout << "Something!\[2J";
Nearly right. The \ alone isn't the ANSI escape character though, you need \033 (that's 27 in octal)
cout << "Something!\033[2J";

You could also do it like
#define ESC "\033"
cout << "Something!" ESC "[2J";

or for even more readable
#define ESC "\033"
#define CLEAR "[2J"

cout << "Something!" ESC CLEAR;

(Note: such short-string #defines are likely to conflict with things in header files so you should probably be a bit more verbose in practice.)

Joda
Apr 24, 2010

When I'm off, I just like to really let go and have fun, y'know?

Fun Shoe
Yeah, I read that I can define them as char variables so in practice I'll probably define a global const char variable like this:

const char CLEAR = '\033[2J';

and use it like this:

cout << "Something!" << CLEAR;

and just use that to avoid confusing myself with concepts I haven't even learnt about yet (i.e. #define) so I at least have some faint idea what I'm doing.

Thanks a lot for your help :)

Edison was a dick
Apr 3, 2010

direct current :roboluv: only

Joda posted:

const char CLEAR = '\033[2J';
The compiler should catch this anyway, but that's 4 characters worth. You probably want const char[] CLEAR = "\033[2J";

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.

Joda posted:

It should be mentioned that I have no prior experience with programming before starting to read this book.
I recommend that beginners read The Practice of Programming. It's a well-written book that covers several fundamental subjects. It also contains many exercises and projects that are more interesting than printing colored text.

Joda
Apr 24, 2010

When I'm off, I just like to really let go and have fun, y'know?

Fun Shoe

Mustach posted:

I recommend that beginners read The Practice of Programming. It's a well-written book that covers several fundamental subjects. It also contains many exercises and projects that are more interesting than printing colored text.

The part about coloured text (and more importantly, clearing the console) was more about also doing some practice on UI design while further familiarising myself with C++. Knowing how to do that wasn't by any means an ends by themselves, but more a way for me to have some kind of tools, no matter how basic, to experiment with making my applications easier to understand and use.

Like I already said I'm almost done with an introductory book, and I'd say it's done a pretty good job of making me understand the concepts and syntax of C++ at a basic level, and before moving on I'll try and make some applications on my own.

Elfforkusu
Jan 15, 2011

That Turkey Story posted:

That's a really big gap, to say the least :p
I guess, but I don't think there's anything bad about not using templates.

IMO, templates ought to be the last thing a C++ programmer learns how to use. Code without them for a while, they're gross and scary and will get you into all sorts of pain if you don't know what you're doing. Also, horrific compile times.

Even now I feel terrible whenever I use them.

litghost
May 26, 2004
Builder

Elfforkusu posted:

I guess, but I don't think there's anything bad about not using templates.

IMO, templates ought to be the last thing a C++ programmer learns how to use. Code without them for a while, they're gross and scary and will get you into all sorts of pain if you don't know what you're doing. Also, horrific compile times.

Even now I feel terrible whenever I use them.

As in you feel terrible every time you std::vector? Or when you write new classes/functions with templates?

That Turkey Story
Mar 30, 2003

Elfforkusu posted:

I guess, but I don't think there's anything bad about not using templates.
I didn't say it was bad to not use templates, just that templates are a gigantic portion of the language. They are pretty much unarguably the single most complicated part of C++ and even if you personally don't create lots of templates, they are still used in the vast majority of the standard library. If you don't "know" templates to a reasonable degree, it's hard to say you really know C++ (in the sense that anyone really can, heh).

That said, templates are awesome and powerful and you're really missing out if you don't understand them, even if you decide not to use them in practice.

Blotto Skorzany
Nov 7, 2008

He's a PSoC, loose and runnin'
came the whisper from each lip
And he's here to do some business with
the bad ADC on his chip
bad ADC on his chiiiiip
TTS, you mentioned on Russ Cox's blog that you think generic programming without runtime costs could be implemented using something simpler than C++ templates. Can you sketch out how this sort of thing might be done?

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed
Templates (and things made possible by templates) are the only thing that makes coding in C++ even vaguely tolerable.

That Turkey Story
Mar 30, 2003

Otto Skorzeny posted:

TTS, you mentioned on Russ Cox's blog that you think generic programming without runtime costs could be implemented using something simpler than C++ templates. Can you sketch out how this sort of thing might be done?

It's an idea that needs to be fleshed out. A lot of it is syntactic changes over what is the C++ template system, but the main win is that with a concept system already present you should be able to eliminate much of the need for template specialization rules and instead deal entirely with concepts and concept-based function overloading. Concepts are complicated beasts on their own, but there really shouldn't be a need for both template specialization and concept-based overloading in a language.

The basic idea is dependent on the fact that all a template really is is a metafunction with different syntax. By that I mean a function template is just a compile-time function that itself yields a function which can be called at runtime (implicit template argument deduction makes this a little less obvious, but it is true), and a type template is a compile-time function that yields a type. All templates also do memoization. Since both function templates and type templates are just fancy compile-time functions, you can apply concept-based overloading in just the same way as you do any other function.

My underlying implication here is that metafunctions and regular functions should be the same, and overload rules should be unified. Functions should be able to return compile-time values and types and take compile-time parameters directly, rather than the C++ approach of having to use implicit or explicit template arguments for such compile-time data. C++0x constexpr gets half-way there, but a full solution would be a way to allow such a qualifier to be applied to some, but not necessarily all parameters. This removes the need for the C++ hacks like at_c templates for tuples and power_c templates for units, where you pass your compile-time data as explicit template parameters and your runtime data as function arguments to the instantiated template. Once you do this and unify metafunctions with functions, and given that you have a concept system in place, you can use concept-based overloading to do what you would currently use template specialization for.

That's the general idea -- instead of having a template system for metafunctions, expand the capabilities of functions, then use concept-based overloads rather than template specialization. You shouldn't have to have two languages in one simply to deal with compile-time data and run-time data. In the end, many of the complexities are still there in some form, but specialization in particular is removed, and a lot of the hairier details are more hidden from users of the language when compared to C++. As a whole it should be much more consistent and easier to learn than a language like C++, but should be able to generate equivalent code.

Plorkyeran posted:

Templates (and things made possible by templates) are the only thing that makes coding in C++ even vaguely tolerable.

Seconded. Well, that and RAII.

Paniolo
Oct 9, 2007

Heads will roll.

Elfforkusu posted:

I guess, but I don't think there's anything bad about not using templates.

IMO, templates ought to be the last thing a C++ programmer learns how to use. Code without them for a while, they're gross and scary and will get you into all sorts of pain if you don't know what you're doing. Also, horrific compile times.

Even now I feel terrible whenever I use them.

Is this a fakepost meant to epitomize every stereotype of the C++ hater who knows jack poo poo about the language?

If not, "gross and scary and painful and horrific" isn't exactly saying anything at all other than you don't understand a significant part of the language and are making strange excuses not to learn it. They're a feature of a programming language, not monsters under your bed.

Paniolo fucked around with this message at 08:35 on Apr 10, 2011

raminasi
Jan 25, 2005

a last drink with no ice
In C++0x, how can I append the contents of a temporary (rvalue) sequence to an existing sequence? I feel like there should be a simple way to do it but I can't figure out what it is. Basically:
code:
some_sequence_t generates_a_temporary();

void func(some_sequence_t & existing) {
    auto temp = generates_a_temporary();
    std::move(temp.begin(), temp.end(), std::back_inserter(existing));
}
Is there a way to do that without temp? Or should I assume I have a Sufficiently Smart Compiler?

ctz
Feb 6, 2003

Edison was a dick posted:

The compiler should catch this anyway, but that's 4 characters worth.

5.

Neat Machine
May 5, 2008

heh
Is it possible to pass a single (and not predefined) element of a structure to a parameter?

For instance:

code:
struct Stats {
	int health, mana;
	int strength, vitality, agility;
	int intelligence, willpower;
};
code:
class Character : GameObject {
...

Stats base_stats;

public:
...

void change_stat(std::string stat_name, int magnitude) {
	base_stats.stat_name =+ magnitude;
}

...
};
Or do I just need to create a separate function for each element?

Neat Machine fucked around with this message at 23:18 on Apr 10, 2011

OddObserver
Apr 3, 2009
Pass a pointer (or a reference).

Adbot
ADBOT LOVES YOU

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

GrumpyDoctor posted:

In C++0x, how can I append the contents of a temporary (rvalue) sequence to an existing sequence? I feel like there should be a simple way to do it but I can't figure out what it is. Basically:
code:
some_sequence_t generates_a_temporary();

void func(some_sequence_t & existing) {
    auto temp = generates_a_temporary();
    std::move(temp.begin(), temp.end(), std::back_inserter(existing));
}
Is there a way to do that without temp? Or should I assume I have a Sufficiently Smart Compiler?

You should assume you have a Sufficiently Smart Compiler. No matter what you do, there will be a local sequence object in func. With any self-respecting C++ compiler, that local sequence will be directly initialized by generates_a_temporary() with no unnecessary copies, regardless of whether it's a local variable or just a temporary.

Now, it would matter if generates_a_temporary() actually returned a reference to a sequence, in which case the code as written above would actually do a copy that it's pretty unlikely that your compiler would be able to eliminate.

rjmccall fucked around with this message at 23:29 on Apr 10, 2011

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply