Tuesday, July 14, 2009

User-friendly compile errors for templates in C++0x

The C++0x features decltype, static_assert and the "new function declarator syntax" can be combined with our old friend SFINAE to generate nicer template compile errors.

As a simple example, consider a container class similar to std::set. Normally if you just declare a variable

set<my_type> s;

it will compile without error even if my_type has no operator<. You will only get an error when you try to call a set member function, such as insert(). Worse still, the errors tend to be quite verbose. (Too verbose for me to want to paste here, anyway.) It would be really nice to generate a short, readable error at the point of the original variable declaration. Let's see how we can do just that in C++0x.

First, we need to write a compile-time test for operator<. This is where SFINAE, decltype and the new function declarator syntax come together. We write the test function:

auto less_than_test(const T* t)
-> decltype(*t < *t, char(0));

and the fallback overload:

std::array<char, 2> less_than_test(...);

The trick here is that, according to the C++0x grammar, we have:

decltype ( expression )

and

expression:
assignment-expression
expression , assignment-expression

This means that the first overload uses decltype to do two things: it makes the overload a viable candidate only if the expression *t < *t is valid; and it says the overload returns a char.

Second, we can use sizeof to determine which of the overloads is selected for a given type T, and static_assert to generate a readable error:

template <typename T>
class set
{
public:
static_assert(
sizeof(less_than_test((T*)0)) == 1,
"type T must provide operator<");
};

The g++ 4.4 compiler then gives the following output on the original variable declaration:

test.cpp: In instantiation of set<my_type>
test.cpp:21: instantiated from here
test.cpp:13: error: static assertion failed:
"type T must provide operator<"

It works with function templates too. To add a check to Asio's async_read function's ReadHandler parameter, I could write the check as follows:

template <typename T>
auto read_handler_test(T* t)
-> decltype(
(*t)(
*(const error_code*)0,
(const std::size_t)0),
char(0));

std::array<char, 2> read_handler_test(...);

template <..., typename ReadHandler>
void async_read(..., ReadHandler handler)
{
static_assert(
sizeof(read_handler_test(&handler)) == 1,
"ReadHandler type requirements not met");
...
}

Perhaps with a touch of macro magic, checks of this sort could become quite easy to write.

"Hang on, what about C++0x concepts?" I hear you ask. What are they? ;-)

23 comments:

john said...

آهنگ جدید
سینا سرلک بدون تو
دانلود آهنگ بهنام بانی زخم کاری
آهنگ مسعود صادقلو زندگی خودمه

Unknown said...

바카라사이트 Thanks for sharing the informative post. If you are looking the Linksys extender setup guidelines . so, we have a best technical expert for handlings your quires. for more information gets touch with us

Unknown said...

카지노사이트 Great writing to see, glad that google brought me here, Keep Up cool job

Unknown said...

스포츠토토 I constantly spent my half an hour to read this web site’s content daily along with a cup
of coffee.

Unknown said...

토토사이트 I was able to find good information from your content.

Kaylee Brown said...

Thanks for sharing this outstanding post with such novice people like us. This article is helpful for both those who offer and those who seeking programming help online.

ethan potter said...

Canon IJ Network Tool is a toolkit software with the options to keep a check on most of your Canon printer network settings and adjust them according to your requirements. The Canon IJ Network tool will get you through the network settings uninterruptedly. Canon IJ Printer Utility is a complete software package meant to adjust and modify the configurations of your printer device as per the requirement.

Max Turner said...


Visit
www.hp.com/go/wirelessprinting and open the door to the world of HP smart printing solutions. HP wireless printer is a versatile printing device that helps you print, scan, copy and fax your documents as per the requirement.
Visit ij.start.canon | ij.start canon and find out the best way to download Canon printer drivers. Canon printers are ideal for every situation wherever you need a document, paper, or photo print or even if you wish to scan, fax, and do more ijstart.canon will make you learn how to set up a canon printer to get advanced printing features.

keonhacai said...

Hello, I'm happy to see some great articles on your site. Would you like to come to my site later? My site also has posts, comments and communities similar to yours. Please visit and take a look keonhacai


steeve00004 said...

You might be aware of using the PayPal Login and it is not wrong to say that Paypal is one of the best, user-friendly payment platforms. Moreover, it facilitates payments that take place via online transfers between different parties. The PayPal credit login platform allows every individual to create an account on its platform that links the user to its account. Once you made an account via PayPal account login credentials you can access an account using identification and the proof of funds as prompted. The users can begin to send or to receive the payments from their PayPal login account online or via the company’s app. Paypal provides many services that you can use both for personal or business uses. It moreover allows the user to make payments online or to transfer money.
For More Information Visit Our Site:
PayPal Login
PayPal Login
AOL MAIL LOGIN
TURBOTAX LOGIN
TUBI.TV/ACTIVATE
tv youtube com start
tv.youtube.com/start

메이저토토 said...

Hello, I read the post well. 메이저토토 It's a really interesting topic and it has helped me a lot. In fact, I also run a website with similar content to your posting. Please visit once

olivila jhon said...

Make sure the surface where you are placing the printer is clean and close to Pc or laptop.Check the shipped components with your inkjet printer
http //ij.start.canon,
https //ij.start.cannon

olivila jhon said...

Allows you to download, install, and configure setup on your PC, Mac and smartphones as well. Canon ij setup is the software to install Canon printer wirelessly.
ij.start.canon,
ij.start canon

ethan potter said...

Canon IJ Network Tool will get you through the network settings uninterruptedly. It is essentially required when you are attempting to get your printer connected to a different network because a new network tends to reset the printer’s existing network settings.The Canon IJ Printer Utility can be used to keep a check on your printer’s ink levels and cartridges and clean the ink tanks and paper feed rollers. Also, you can make adjustments to your Canon printer’s power settings.

Anonymous said...

This is really nice.
hbomax/tvsignin
disneyplus.com/begin
hbomax.com/tvsignin
disneyplus com login begin

James K. said...

The ij.start.cannon setup process for every Canon model is almost similar, however the download through https //ij.start.cannon and http //ij.start.cannon installation process may differ. you can also visit canonsetup-canon.com/ijsetup website for same. Https //ij.start.cannon.Depending on your requirement, it offers a type printer including PIXMA, SELPHY, MAXIFY, etc. canon.com/ijsetup

Max Turner said...

Once you are done with the driver setup via canon.com/ijsetup , you will have to insert a pile of pages into the printer tray for printing the documents..

Visit ij.start.canon | ij.start canon and find out the best way to download Canon printer drivers.
All-in-one Canon Inkjet printers are suitable for home, business, school, and others to improve productivity. You can easily set up your Canon printer through drivers from Canon.com/ijsetup , wireless connection, USB, and a few components.

Unknown said...

Canon drivers fully support and assists for all compatible products for all Window versions. We offer the required data to configure, utilize and install your Canon products on your Windows PC.canon is completely safe and secure. ij.start.canon |
ij.start.cannon

Patrika Jones said...

Nice...
It's a very powerful article. I really like this post. Thank you so much for sharing this.

ij.start.cannon
ij.start.canon

Unknown said...

Hotel & Casino, Dubai, UAE - Air Jordan23
Guests where can i find air jordan 18 retro men can try the outdoor pool. If you're 불법 토토사이트 샤오미 looking for a pool in the centre, the air jordan 18 retro men blue shop Hotel how to order air jordan 18 retro men & Casino, Dubai, UAE has a wide best air jordan 18 retro red suede range of outdoor swimming pools.Hotel class: Adults onlyRooms: 2616 sq ft

Patrika Jones said...

Nice post. Thanku so much to share this with us.

putlocker
kissanime

Travis Wills said...

Connecting the Cricut machine to a PC is enough, but setting up the machine on a mobile device makes it portable and easy to craft. If you want a direct and easy way to craft through your Android or iOS phone, then go through the to Cricut.com/setup |Cricut com setup windows | cricut.com setup connect to Cricut.

shaunagrant said...

Cricut setup allows you to enter the world of designs and patterns to evoke your
craftsmanship for the development of unparalleled crafts and designs. Being an art lover, you must have craved conceiving your conceptual patterns into reality. cricut.com setup windows