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
nielsm
Jun 1, 2009



TheMover posted:

For background: I'm programming a robot, I want the robot to execute tasks on its own but allow the user to type some command into the console and be able to take control from it at any time.

Either threading, as you mention yourself, or non-blocking I/O.

I don't think the C++ iostreams can deal with non-blocking input so you would have to use the operating system's call interface for that.
The idea behind non-blocking I/O is that you once in a while poll whether there is anything ready to read, if there is you can then read it and handle it, if there isn't do whatever else you need to. Since non-blocking I/O requires you to poll it's not terribly efficient but it's somewhat easier to get right than threading.

If you want to do a threading solution, I would suggest having the user input thread do all the reading and parsing of commands and pack it into a format that could easily be used by the actual control code, then send that off into a threadsafe queue (find a lock-free implementation!) which the control thread then checks for new stuff whenever it can.

Adbot
ADBOT LOVES YOU

schnarf
Jun 1, 2002
I WIN.

Bisse posted:

The problem is VC++ 2010 refuses to compile saying the option /O-something (inline) is incompatible with the option /Z-something (debug). AFAICT it does that for all optimization choices. I'm using Express though, dunno if that makes a difference.

There's a pragma to selectively enable optimization for specific functions, maybe that would help: http://msdn.microsoft.com/en-us/library/chh3fb0k(v=vs.80).aspx

shrughes
Oct 11, 2008

(call/cc call/cc)

nielsm posted:

Either threading, as you mention yourself, or non-blocking I/O.

I don't think the C++ iostreams can deal with non-blocking input so you would have to use the operating system's call interface for that.
The idea behind non-blocking I/O is that you once in a while poll whether there is anything ready to read, if there is you can then read it and handle it, if there isn't do whatever else you need to. Since non-blocking I/O requires you to poll it's not terribly efficient but it's somewhat easier to get right than threading.

You can use epoll or select (or your OS's equivalent) and that would be nice for selecting over the several file descriptors you have.

nielsm posted:

then send that off into a threadsafe queue (find a lock-free implementation!)

An implementation with O(1) operations inside of a spinlock will suffice. For user commands, that is.

TheMover posted:

blah iostreams

loving avoid iostreams.

chglcu
May 17, 2007

I'm so bored with the USA.

schnarf posted:

There's a pragma to selectively enable optimization for specific functions, maybe that would help: http://msdn.microsoft.com/en-us/library/chh3fb0k(v=vs.80).aspx

#pragma optimize is also disabled by the /ZI option, apparently. From http://msdn.microsoft.com/en-us/library/958x11bc(v=VS.100).aspx:

MSDN posted:

/ZI
Produces a program database, as described above, in a format that supports the Edit and Continue feature. If you want to use Edit and Continue debugging, you must use this option. Because most optimizations are incompatible with Edit and Continue, using /ZI disables any #pragma optimize statements in your code.

chglcu fucked around with this message at 08:44 on Jan 12, 2012

nielsm
Jun 1, 2009



I can't remember Edit And Continue ever working for me, so personally I wouldn't mind disabling it.

TheMover
Jun 24, 2010

nielsm posted:

very helpful words

shrughes posted:

even more helpful words

Thanks you two! Hopefully I won't come back here crying for help again soon. You've got me curious though, I'm probably just being naive as hell here, but why avoid iostreams?

tractor fanatic
Sep 9, 2005

Pillbug
My program checks for a bool condition inside a loop. Is there a way I can move the boolean check outside the loop without copy/pasting the whole thing?

code:
for (...){
    if (condition){
        do something
    }
    else{
        something else
    }
}
vs

code:
if (condition){
    for (...){
        do something
    }
}
else{
    for (...){
        something else
    }
}
If the bool condition is some parameter that doesn't change, will the compiler be smart enough to move the boolean check outside the loop?

shrughes
Oct 11, 2008

(call/cc call/cc)

tractor fanatic posted:

My program checks for a bool condition inside a loop. Is there a way I can move the boolean check outside the loop without copy/pasting the whole thing?

The second example is not actually ugly so you should go with it. It's only superficially ugly.

tractor fanatic posted:

If the bool condition is some parameter that doesn't change, will the compiler be smart enough to move the boolean check outside the loop?

If it's a local variable, maybe.

If you really care about performance there, you probably won't want to rely on the compiler anyway.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
This optimization is called loop-unswitching, and most compilers provide it. It's a "dangerous" optimization, though, because cloning the loop tends to increase code size, so massive unswitching can hurt whole-system performance even while helping specific benchmarks.

It's also not uncommon for the compiler to not be able to prove the loop-invariance of a condition; that's why shrughes mentions local variables, which are much easier to prove things about.

tl;dr: shrughes is right.

Princess Kakorin
Nov 4, 2010

A real Japanese Princess
I've been tinkering with a map-drawing system for 2D tilebased games.
The way I have it set up now is a MAP object that has an array that holds TILE objects and a TILESET object that holds the image that TILE objects would reference as well as all TILE objects that relate to the TILESET.

Example of a TILESET object:
code:

typedef struct s_GrassTown : TILESET
{
  image = loadimage("grasstown_ts.bmp");

  //All TILE objects that belong to GRASSTOWN
  typdedef struct s_Grass : TILE
  {
   char ID = 'G';
   ...
  } GRASS;

  typedef struct s_Water : TILE
  {
   char ID = 'W';
   ...
   } WATER;

} GRASSTOWN;

My problem is, I can't think of a decent way to populate the TILES[] in the MAP object.
Right now, I have a putTile(char id) function in TILESET, that returns a TILE based on the id passed through. When a MAP is created, it reads in a stream of characters, passing each character through putTile and putting the returned TILE into the TILE[].
Is there a more efficient way to handle this? I feel like there is, but I don't see it.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
Do you actually need to transform the identifiers into TILEs when you populate the map?

Do you actually need to put dozens of copies of identical TILEs into the map instead of just using a pointer?

What's the difference between a pointer-to-TILE and an offset-into-an-array-of-TILEs?

EnzoMafo
Jul 29, 2008
Hello fellows. My question is not directly related to the workings of C++, so I apologize if this is the wrong thread. I have been asked to add use of syslog for our application running on Red Hat. I am having some problems. Leaning heavily on what sparse examples I could find on google and this man page , I came up with this little test:

code:
int main(int argc, char** argv)
{
  openlog("testlog", LOG_CONS, LOG_LOCAL0);

  syslog(0, "%s", argv[1]);

  closelog();
}
Now, that seems to work if I want to throw the message in "/var/log/messages". However, I'd like for the program which uses it to have its own log file. It seems like this should be possible, but I am having trouble discerning from the man pages how to do it.

I've found mention of defining my own "facility" in /etc/syslog.conf, a file that contains entries such as
code:
*.info;mail.none;authpriv.none;cron.none		/var/log/messages
. How would I specify my custom added "facility" in my code? According to the previously linked man page, the facility is an int? Any help or advice would be much appreciated.

Gerblyn
Apr 4, 2007

"TO BATTLE!"
Fun Shoe

Princess Kakorin posted:

Is there a more efficient way to handle this? I feel like there is, but I don't see it.

With regards to how you populate the tile map, your solution seems quite reasonable to me. You have a map file of characters that you can read and edit by hand, so you don't need to write an editor. In terms of speed, it sounds as if it would be quite fast if written correctly (e.g. by using the character to find the tile in a look-up table or a map). Also, it's not as if you're doing this at run time, so speed isn't that important anyways. About the only limitation that's a pain is what happens if you have more tile types than characters.

The next step would involve having a more complex file format, where you can store more data about each tile (e.g This is a grass tile, there is a treasure chest on it, it contains X items). Unless you really love editing text files, this would probably involve writing an editor for though.

What exactly do you want to improve about what you've got?

Also, defining a class in code for each tile type seems to be a bit crazy. If I were to make it, I'd make that data driven. So I'd have a config file that defines each tile set, containing something like this XML maybe:

code:
<tileset>
  <name>Grass Tiles</name>
  <filename>grass_tiles.bmp</filename>
  <tile>
    <name>Short Grass</name>
    <id>A</id>
    <top_left_corner x="0" y="0"/>
    <bottom_right_corner x="16" y="16"/>
  </tile>
  .. more tile definitions ..
</tileset>
And then write a generic tile set class that contains a map/list of generic tile classes, which I'd set up using data from the file. This way you can add as many tile sets as you like without having to recompile the code each time.

pseudorandom name
May 6, 2007

EnzoMafo posted:

I've found mention of defining my own "facility" in /etc/syslog.conf, a file that contains entries such as
code:
*.info;mail.none;authpriv.none;cron.none		/var/log/messages
. How would I specify my custom added "facility" in my code? According to the previously linked man page, the facility is an int? Any help or advice would be much appreciated.

You can't define your own facility, you can only choose from the fixed list you can find in the syslog(3) man page. Typically daemons that log to files in /var/log are doing it themselves without involving syslog at all, because syslog is terrible.

Alternately, depending on exactly how terrible your syslogd is, you may be able to filter your daemon's output to its own log file based on e.g. the ident you pass to syslog(3), but how you go about doing that is dependent on which syslogd you're using.

InAndOutBrennan
Dec 11, 2008
I'm probably missing something.

Say I have a class with a method. When I set up the class, at runtime I want the method to do either something A or something B. But I want it to do the same thing every time.

Pseudocode:
code:
bool quoted;

if(user_input) {
	quoted = false;
} else {
	quoted = true
}

my_reader = new CSVReader(quoted);
my_reader.get_row();
Depending on the value of quoted I want get_row() to do different things without having to if() stuff in the method every time i call it. I looked at function/method pointers but that seemed overly complicated.

I can solve it by making two different classes inherit from a base class but I'm curious as to if it's possible some other way?

brosmike
Jun 26, 2009

woptsufp posted:

Depending on the value of quoted I want get_row() to do different things without having to if() stuff in the method every time i call it. I looked at function/method pointers but that seemed overly complicated.

I can solve it by making two different classes inherit from a base class but I'm curious as to if it's possible some other way?

Theoretic answer:
An option you haven't brought up is making the CSVReader a class template with quoting as a template parameter - that doesn't complicate your instantiation code any more than using different non-template classes would and it's possible to use it such that you avoid the vtable lookup you'd incur from using the class hierarchy. You could either specialize the method in question based on the quoted value or just use an if statement on what is now a compile-time constant, since any non-brain-damaged compiler will optimize it out. Of course, you can't use your quoted variable from the code snippet above as the template parameter to instantiate with directly (it isn't known at until run time), but you can get around that in a few ways:

code:
template <bool quoted>
void parse_the_data() {
    CSVReader<quoted> reader();
    reader.do_stuff();
}
int main() {
    ...    
    if(quoted) {
        parse_the_data<true>();
    } else {
        parse_the_data<false>();
    }
    ...
}

// or make the CSVReader template extend a CSVReaderBase and...
...
CSVReaderBase* reader;
if(quoted) {
    reader = new CSVReader<true>();
} else {
    reader = new CSVReader<false>();
}
reader->do_stuff();
...
Pragmatic answer:

For the overwhelming majority of programs, the difference in runtime overhead between the options you mention is completely insignificant. This is especially true for something like a CSVReader where you're much more likely to be constrained by file IO than anything else and probably won't have many instances of the class around. Unless you've actually got evidence that it's a performance issue, the "right" answer is probably "whatever's simplest for you to implement and your maintainers to understand and update", which is probably just using the if statement.

Using a class hierarchy to switch on this option is almost certainly a poor choice. What happens if you later discover you need to choose between commas and tabs, too? Do you have a QuotedCSVReader, UnquotedCSVReader, QuotedTSVReader, and UnquotedTSVReader then? What about supporting the first line being column names - now do you have 8 classes?

As a side-note, if you're trying to implement a generic CSV reader and not something specific to files you control, you should be aware that most (though admittedly not all) CSV specifications (eg, RFC 4180) allow a mix-and-match of quoted and unquoted values within the same file.

Dicky B
Mar 23, 2004

Policy classes.

code:
struct SomethingApolicy
{
    void get_row() {}
};
struct SomethingBpolicy
{
    void get_row() {}
};
template <class GetRowPolicy>
class CSVReader : public GetRowPolicy
{
};
...
if(quoted)
{
    CSVReader<SomethingApolicy> reader;
    get_row(); // Calls SomethingApolicy::get_row
}
else
{
    CSVReader<SomethingBpolicy> reader;
    get_row(); // Calls SomethingBpolicy::get_row
}

InAndOutBrennan
Dec 11, 2008

brosmike and Dicky B posted:

...

Thanks!

I'm mostly using this as a learning/experimenting thing and CSV-files is something I'm familiar with and do a lot of work with so that's why I'm using them as subject matter.

Regarding the other things (separator, column names etc), those are common to both cases so I have to take care of them regardless.

I'll poke around the stuff you mentioned and see what I can pick up.

Paniolo
Oct 9, 2007

Heads will roll.
Is there anything in boost::type_traits that will return just the root type?

For example:

code:
root_type<Foo*>::type == Foo
root_type<Foo&>::type == Foo
root_type<Foo[]>::type == Foo
root_type<Foo[][]&>::type == foo
I doubt it would be too hard to write one, just seems strange that it wouldn't already be in boost.

That Turkey Story
Mar 30, 2003

Paniolo posted:

Is there anything in boost::type_traits that will return just the root type?

For example:

code:
root_type<Foo*>::type == Foo
root_type<Foo&>::type == Foo
root_type<Foo[]>::type == Foo
root_type<Foo[][]&>::type == foo
I doubt it would be too hard to write one, just seems strange that it wouldn't already be in boost.

It's probably not in boost because there's not really a use-case for it that I can think of. You can use the other type traits to make what you want if you really think you need such a metafunction. Just out of curiosity, how far do you want to go and for what purpose would you be using it? I.E. Would root_type< int* (*)[5] >::type be int* or int, and why?

Also, Foo[][]& is not a type. Neither is Foo[][] for that matter.

Paniolo
Oct 9, 2007

Heads will roll.
This is for a reflection system where I have something that looks like this:

code:
template <typename T>
Type GetType()
{
    return TypeHolder<T>::Type;
}

template <typename T>
Type GetType(const T& t)
{
   return GetType<root_type<T>>();
}
Where root_type is the non-existent metafunction which strips away CV-qualifiers, reference, pointer, array extents, etc, as TypeHolder<const Foo>::Type would result in a linker error, since those are instantiated only for the root Types.

It's trivial enough to do by comining remove_cv, remove_ref etc., I was just curious if something already existed along those lines.

tractor fanatic
Sep 9, 2005

Pillbug
code:
template <typename T>
class A{
    int a, b;
public:
    friend void swap(A<T> & l, A<T> & r){
         std::swap(l.a, r.a);
         std::swap(l.b, r.b);
    }
};
Intellisense insists that a and b are inaccessible, but it compiles just fine. I understand VC Express 2010 uses EDG for its intellisense, but MSVC for the actual compiler. Is intellisense wrong here, or is MSVC?

delta534
Sep 2, 2011
I'm pretty sure that Intellisense is wrong here, because this is equivalent and does not cause any errors with Intellisense.
code:
template <typename T>
template <typename T>
class A{
    int a, b;
public:
    template<typename T>
    friend void swap(A<T> & l, A<T> & r);
};
template<typename T>
void swap(A<T> & l, A<T> & r){
    std::swap(l.a, r.a);
    std::swap(l.b, r.b);
}
edit. fixed a error with the code.

delta534 fucked around with this message at 20:56 on Jan 15, 2012

That Turkey Story
Mar 30, 2003

tractor fanatic posted:

Intellisense insists that a and b are inaccessible, but it compiles just fine. I understand VC Express 2010 uses EDG for its intellisense, but MSVC for the actual compiler. Is intellisense wrong here, or is MSVC?

Intellisense is wrong. Just a shot in the dark to help it out a little bit -- take the <T> part out of the parameters in your swap declaration and see if intellisense can reason about it a little better. Realistically this shouldn't change anything at all, but you never know just what's confusing intellisense.

delta534 posted:

I'm pretty sure that Intellisense is wrong here, because this is equivalent and does not cause any errors with Intellisense.
code:
template <typename T>
class A{
    int a, b;
public:
    friend void swap(A<T> & l, A<T> & r);
};
template<typename T>
void swap(A<T> & l, A<T> & r){
    std::swap(l.a, r.a);
    std::swap(l.b, r.b);
}

That's not actually equivalent and should NOT compile. Your friend declaration is of a non-template while your implementation is a template. In other words, the swap template is not actually a friend and your actual friend is not defined. So the swap template shouldn't be able to be instantiated since it doesn't have access to A's members.

Edit: *pushes glasses along ridge of nose* Your edit still has a mistake :|

That Turkey Story fucked around with this message at 22:22 on Jan 15, 2012

Knyteguy
Jul 6, 2005

YES to love
NO to shirts


Toilet Rascal
Is it possible to dissect every singular digit from a sum and put them into an array?

i.e.:
if 101 * 101 = 10201
array = 1, 0, 2, 0 ,1

That Turkey Story
Mar 30, 2003

Knyteguy posted:

Is it possible to dissect every singular digit from a sum and put them into an array?

i.e.:
if 101 * 101 = 10201
array = 1, 0, 2, 0 ,1

Yeah.

Knyteguy
Jul 6, 2005

YES to love
NO to shirts


Toilet Rascal

That Turkey Story posted:

Yeah.

Cool, do you mind informing me what the method is? :)

That Turkey Story
Mar 30, 2003

Use division and modulus.

Paniolo
Oct 9, 2007

Heads will roll.

Knyteguy posted:

Cool, do you mind informing me what the method is? :)

Well I was going to emptyquote the OP where it says this thread isn't for homework help but it's either been edited out or I only imagined it was ever there in the first place.

So, to answer your question, think about what happens when you divide an integer by ten.

shrughes
Oct 11, 2008

(call/cc call/cc)

Knyteguy posted:

Is it possible to dissect every singular digit from a sum and put them into an array?

i.e.:
if 101 * 101 = 10201
array = 1, 0, 2, 0 ,1

That's not a sum.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
Whenever a question comes up like this I'm always tempted to provide an answer that appears to work if you just run it, but is obviously copy-pasted by someone who doesn't understand how it works if they actually hand it in.

Knyteguy
Jul 6, 2005

YES to love
NO to shirts


Toilet Rascal

shrughes posted:

That's not a sum.

I've always thought sum is synonymous with total. What would it be called properly?

Jabor posted:

Whenever a question comes up like this I'm always tempted to provide an answer that appears to work if you just run it, but is obviously copy-pasted by someone who doesn't understand how it works if they actually hand it in.

This isn't homework... I'm trying to learn c++ independently (it's my first day ever using c++). I'm actually working on a projecteuler.net problem.

Thanks for the help though guys, this poo poo is racking my brain, and it's awesome :).

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

Jabor posted:

Whenever a question comes up like this I'm always tempted to provide an answer that appears to work if you just run it, but is obviously copy-pasted by someone who doesn't understand how it works if they actually hand it in.

Like this?

EDIT: Oh, Project Euler. Assuming you're doing the problem I think you're doing, you don't need the array, you just need to keep a running accumulator.

Suspicious Dish fucked around with this message at 04:23 on Jan 17, 2012

shrughes
Oct 11, 2008

(call/cc call/cc)

Knyteguy posted:

I've always thought sum is synonymous with total. What would it be called properly?

A product. Ten thousand two hundred one. Negative negative ten thousand two hundred one.

It's certainly a sum: the sum of ten thousand two hundred and one. Or the sum of five thousand two hundred and ten thousand one. Or..

I'm jibing you anyway, it's just a number. Your real question is, "How do I put the digits of a number in an array?" as far as I can tell.

shrughes fucked around with this message at 04:50 on Jan 17, 2012

Vanadium
Jan 8, 2005

Jabor posted:

Whenever a question comes up like this I'm always tempted to provide an answer that appears to work if you just run it, but is obviously copy-pasted by someone who doesn't understand how it works if they actually hand it in.

How about this simple solution using the stock techniques of recursion and pattern matching?

http://codepad.org/9IpB9TTs

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!

Vanadium posted:

How about this simple solution using the stock techniques of recursion and pattern matching?

http://codepad.org/9IpB9TTs
Am I correct in thinking that the 'digits' part of that is completely resolved at compile-time not at run-time?

Vanadium
Jan 8, 2005

Practically, yes. It runs the constructors at run time to write the value of the char literals into those member variables, but it all gets laid out at compile time. It couldn't do anything with user input at runtime.

That's just as well, because it only works for numbers that are palindromes in base 10. :ssh:

OddObserver
Apr 3, 2009
Where does the null termination come from?

That Turkey Story
Mar 30, 2003

OddObserver posted:

Where does the null termination come from?

Nowhere -- there's a few problems with it, I think on purpose.

Adbot
ADBOT LOVES YOU

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!

Vanadium posted:

Practically, yes. It runs the constructors at run time to write the value of the char literals into those member variables, but it all gets laid out at compile time. It couldn't do anything with user input at runtime.

That's just as well, because it only works for numbers that are palindromes in base 10. :ssh:
I have to say, that's a work of genius in terms of deliberately answering the question that was asked, and only the question that was asked, carefully avoiding the intent behind the question.

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