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? ;-)

16 comments:

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

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


Anonymous said...

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

Patrika Jones said...

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

putlocker
kissanime

JOIN US HERE said...

Thank you for your hard work! One thing I really want to answer is that a quick fat burning plan is possible with an appropriate diet and exercise. The size of a person affects not only appearance but also quality of life. Self-esteem, depression disorders, health risks, and physical abilities affect weight gain. You can do everything right, but you can still make a profit. In this case, the problem may be the perpetrator. While eating a lot of food instead of enough exercise is usually the cause, general health conditions and traditional prescriptions can greatly increase their size. Thank you for posting it here.

토토사이트링크
토토사이트
바카라사이트
온라인카지노

Cheap Homework Help said...

College is very challenging. You have to study every day and pass your classes. You have to learn a lot of new things. It is not easy, but it is a great opportunity to gain knowledge and get better grades. You need to work hard and dedicate yourself to achieve your goals.

Temika Wiatrak said...

Kindergarten & Pre-school exclusive teaching products around Jabodetabek are exclusive training to get very early younger years working with the first childhood & kindergarten syllabus, as well dad and mom can select to concentrate on ... click https://kursus-akuntansi.netlify.app/kursus-akuntansi-cipete.html for more details

Tiffani Scobie said...

Jabodetabek private tutoring services with teachers coming over to the house. More than numerous active tutors will be ready teach various skills and lessons of the to adults ... visit https://kursus-jerman.vercel.app/kursus-bahasa-jerman-cilincing.html for more information

Guest said...

I don't really know. This site seemed helpful. Drywall Repair & Restoration

Essien said...

I've read some great stuff here. Will definitely bookmark and visit again. I am amazed at the effort you put into creating such an excellent and informative website. Thanks so much for sharing. bill melinda gates college of health admission form

santander personal loan calculator said...

Transform your home with Santander's competitive rates on improvement loans, providing the financial support you need to make significant upgrades and add value to your property. santander home improvement loans

Snuggle hunny kids said...

Thinking asynchronously in C++ is crucial for efficient and responsive programming. Just like Ted Lasso TrackSuit, it's about adaptability and handling tasks with a relaxed yet focused approach.

borokutja companies said...

Thanks for sharing this information which useful and provides an insight.

átvilágítás cégeladás során said...

Amennyiben cégtulajdonos és eladáson gondolkodik, akkor a cégeladás folyamatában az adequit eladó cégek tanácsadás rendelkezésére áll.

Fort Lauderdale's Best Concrete Driveways said...

I really appreciate the diverse range of examples you included. It made the content much more relatable. Thank you!