Log in

No account? Create an account

Advanced C++ Community

About Recent Entries

Ugly C++ technique that I'm still proud of thinking of Sep. 4th, 2009 @ 11:21 pm

This is x-posted from an entry in my journal.

I'm quite pleased with myself. :-) I've been participating on stackoverflow.com recently. HazyBlueDot had an interesting question in which (s)he was trying to use ::boost::function to get around a broken library interface.

In particular, the library interface allowed you to register a callback function, but it did not provide you a way of giving it a void * or something to pass back to you so you could put its call of your function back in context. HazyBlueDot was trying to use boost::function in combination with boost::bind to add in the pointer and then call his own function. The only problem is that the result boost::function object then couldn't produce an ordinary function pointer to pass to the callback.

This, of course, cannot be done in a static language like C++. It requires on the fly generation of first-class functions. C++ simply can't do that. But, there are various interesting tricks you can pull to generate functions at compile time with templates in ways that can help with this problem, even if they can fully solve it.

I'm particularly pleased with my solution, which looked something like this:

Cut so that people who find that source code makes their eyes bleed don't have to lookCollapse )

This basically allows you to automatically generate a 'thunk' function, a normal non-member function that can be passed to the callback, that then calls another function and adds the contents of a global variable you specify as a template parameter. It doesn't fully solve the problem, but it partially solves it. And I think in this case it will do something pretty close to what HazyBlueDot wants.

This should work even if you have the global variable in question inside an anonymous namespace.

Current Mood: pleasedpleased

The new C++0x standard Aug. 27th, 2009 @ 09:19 am

What are your favorite features in the upcoming C++0x standard?

My personal favorites are:

  • rvalue references - I once said that the STL containers should be defined to move things around with the swap operation instead of by using the copy constructor so that auto_ptr would work. My opinion is vindicated by rvalue references and the requirement that the STL containers use move construction.
  • Variadic templates - So much stupid ugliness in Boost is because you can't have templates with variable numbers of arguments. This fixes that.

Current Location: 2237 NW 62nd ST, 98107
Current Mood: curiouscurious

Hardware independent (sort of) compare and swap? Dec. 24th, 2007 @ 10:13 am
Is anyone aware of an existing free-as-in-beer codebase that provides an abstraction for compare-and-swap across common hardware types?

I am writing a fairly simple lock-free buffer type and would like to avoid doing the assembler myself. The platforms which I have an immediate interest in supporting are x86 and SPARC v9: nothing exotic.

I've done some hunting and pleasingly it looks like these atomic ops are quite likely to go into the C++ standard at some point (in C++0F or whatever), however I can't find anything concrete in terms of an implementation yet.

New to threads Dec. 20th, 2007 @ 05:41 pm
I've never written any threaded applications before, but I have one that could probably benefit from it. I'm looking at converting it over using Boost.

I have found the Dr. Dobbs article, which seems to have the best and most numerous examples of Boost threading, but I'm still unclear on how to actually get the different threads to execute in parallel. I'm really just starting out here, so maybe I'm just misinterpreting, but it looks like in the examples the threads are executed serially, which doesn't make any sense. I must misunderstand something.

I admit my impatience with reading the whole article in detail, because my particular application seems--to my naive self--to naturally avoid the major pitfalls of threading.

Basically, it creates a collection of Recipients, and for each recipient:
- queries for some information to email to the recipient
- emails the information to the Recipient
- deletes the database records that led to the email being sent (no two recipients will share a record, and this is MySQL, so there will be no table locks)
- logs the sending of the email in another database table
- updates a record of the last time the user received an email

Rather than processing each recipient serially in a loop, I'd like to be able to spawn a thread for each recipient. I'm thinking that I need to combine all of the per-recipient tasks into a single function and then spawn a new thread of that function for each recipient. Am I on the right track? Do I need to use a thread_group so I can dynamically create threads rather than instantiating specific named threads, as is done in all of the Dr. Dobbs examples?

Here is the gist of the application. The mailer is a functor.

snippetCollapse )

Any applicable advice appreciated. Alliteration optional.

Callback for something that might disappear Oct. 21st, 2007 @ 01:31 am

I wanted to have a fairly robust callback that would call something that might disappear before the callback is triggered. I wanted the callback to simply go dead when its target disappeared.

I thought about it a lot, and I came up with this:

A whole big glob of source codeCollapse )

This results in a lot of overhead per call though. More than I was expecting. And the other problem is that callback functions are limited to functions with a certain signature. You could use boost::bind to bind all the arguments to your callback and store them away safely so it looked like it was void (void), but that seems inelegant and like it wouldn't work well for some situations.

It's pretty easy to do f(g(x)) in boost, but not so easy to do f(g)(x) when f is something that creates a function that largely just needs to pass things along to g.

Is there a way around this?

Current Mood: contemplativecontemplative

Tiered Debugging Aug. 27th, 2007 @ 05:08 am
First off, I would like to thank everyone for the discussion back in the Debugging post

Here is the abbreviated overview of what I created:

Fine grained modularity
Multiple levels of debugging may coexist. The developer may have everything
controlled from the global scope, all the way down to each debug macro having
its own separate state. (Though, doing the latter would probably create a
maintenance nightmare.)

Message stream inserters
Anywhere the macro variable "message" appears, stream inserts (operator <<())
may be used. Thus, for example:

int n = 5;
TD_LOG("current value of n: " << n);

Static compilation
Since every aspect of the structs used to control the behavior of Tiered Debug
are statically defined, the compiler can eliminate any superfluous code.

You can download the code and unit test from here.

If anyone thinks I should clarify the documentation or add in specific examples, go ahead and tell me.

Debugging Aug. 13th, 2007 @ 07:02 am
I've been thinking about ways to allow differing amounts of information to be displayed while debugging a program. And thus I came up with this possible solution. I would like to hear what other people have to think, and would greatly welcome any constructive criticism.

Read more...Collapse )

Just a funny peace of code. How you compiler processes it? Apr. 6th, 2007 @ 08:31 pm
struct A {

template<typename TList>
struct MultipleInheritance :
  public TList::Head,
  public MultipleInheritance<typename TList::Tail>

template <typename T1>
struct RecTList {
  typedef T1 Head;
  typedef RecTList< RecTList<T1> > Tail;

typedef RecTList<A> ARecTList;

class RectClass : public MultipleInheritance<ARecTList> {};

int main() {
  return 0;

Psuedo Stack Trace Via Exceptions Dec. 5th, 2006 @ 10:22 pm
In my post on (bad) optimizations, iamo gifted us with the neat trick of catching exceptions that are thrown in constructor lists (link).

This got me thinking about supporting some type of stack trace in exceptions. Here are my musings:
Read more...Collapse )
Has anyone else done this? Do anyone have pointers / hints?

Optimizations Nov. 11th, 2006 @ 09:42 am
I came across this page of C++ optimizations recently (http://www.custard.org/~andrew/optimize.php). Some of them I consider to be fair, while others I consider to either have hidden pitfalls, or possibly even flat out wrong. Below is a list of my reactions. I would like to hear other people's opinions. Especially if I missed a pitfall or misinterpreted what the optimization was for.
Read more...Collapse )

Lint tools on Windows? Nov. 2nd, 2006 @ 11:04 pm
I saw the comments to a recent entry here talk about lint tools. Do any of you use some form of lint regularly (and do they help you a lot)?

And are there any free ones available for windows and/or osx, that handle C++? I searched for them a few times, and IIRC, I only found one free one that would run on Windows, that handled C only.

Am I nuts? Oct. 25th, 2006 @ 06:20 pm
I'm rather offended, having been bitten by this bug. Why is it even allowed to take a reference to a const reference, if it could be a copy?!?

#include <assert.h>

class Blah
  const unsigned int &myfoo;
  Blah(const unsigned int &p):
    myfoo(p) {}
  const unsigned int getfoo()
    return myfoo;

int main()
  int foo(42);
  Blah baz(foo);


  assert(foo == baz.getfoo());

  return 0;
Current Mood: shockedshocked

Counter of C/C++ source lines and bytes Oct. 6th, 2006 @ 08:49 am
Counter of C/C++ source lines and bytes

MoreCollapse )

C/C++ Program Perfometer Oct. 1st, 2006 @ 09:08 am
The C/C++ Program Perfometer is an open source tool which enables the programmer to measure the comparative performance of a C/C++ program or of separated pieces of code by one of several desired metrics: e.g., time, memory, or metrics defined by the programmer.

C/C++ Program Perfometer has been referenced at the C++ Standards Committee site:
(information announcing C++ - TR 18015 Technical Report on C++ Performance).

Google Groups
Subscribe to comp.lang.c++.perfometer

Browse Archives at groups.google.com

Riddle Me This Aug. 15th, 2006 @ 10:51 pm
Correct me if I'm wrong but aren't programmers just highly intelligent people paid to play with lego?

DevPartner or? Jul. 22nd, 2006 @ 10:49 am
Is there a way to export the output report of the DevPartner (leaks) to any open format, like XML, etc... sorry for the offtopic. I just don't think any other community could possibly help.

Pipelining numerical computation Apr. 11th, 2006 @ 11:49 am
How do you efficiently vectorize std::valarray?

Here's how I did it...Collapse )

C++0x Apr. 10th, 2006 @ 10:58 pm
What's your opinion of the new stuff coming down the pike from the standards committee? Specifically, what do you think of Concepts? For those of you who are unfamiliar with some of the new things arriving in your next C++ standard, here is a brief summary.


A question about derivation and virtual functions Apr. 10th, 2006 @ 12:02 pm

I was surprised by the output of this code using MSVC++ 6:

test codeCollapse )

I expected the output to be 1 2 3 2 2 2; it was 1 2 3 2 3 3. Since id() is not virtual in t2, how can it be overridden in i5, and especially in i6?
This makes so little sense to me, I’m wondering if it’s a compiler error. Does anyone know?

Mar. 24th, 2006 @ 05:11 pm
Today I was asked for simple example of using ADO, C++ and MS SQL Server. I tried to do something understandable, but it is really hard to use ADO in C++.
I have developed solution for this purpose for my company, but it is a set of wrappers for easy using.
I think all of us, who uses ADO in C++, have it's oun unique collection of such libraries :) Am I right? Guys, let's share our experience.
Maybe it would be good to develop some simple and good library that uses ADO as data access library in the heart and upload as GPL to SF.NET.
What you think about it? There is a "simple" example I gave to my friend to enable him to understand how it works :)

Top of Page Powered by LiveJournal.com