Friday, April 09, 2010

System error support in C++0x - part 3

[ part 1, part 2 ]

Enumerators as class constants

As we have seen, the <system_error> header defines enum class errc:

enum class errc
{
address_family_not_supported,
address_in_use,
...
value_too_large,
wrong_protocol_type,
};

the enumerators of which are placeholders for error_condition constants:

std::error_code ec;
create_directory("/some/path", ec);
if (ec == std::errc::file_exists)
...

Obviously, this is because there's an implicit conversion from errc to error_condition using a single-argument constructor. Simple. Right?

It's not quite that simple

There's a few reasons why there's a bit more to it than that:

  • The enumerator provides an error value, but to construct an error_condition we need to know the category too. The <system_error> facility uses categories to support multiple error sources, and a category is an attribute of both error_code and error_condition.
  • The facility should be user-extensible. That is, users (as well as future extensions to the standard library) need to be able to define their own placeholders.
  • The facility should support placeholders for either error_code or error_condition. Although enum class errc provides placeholders for error_condition constants, other use cases may require constants of type error_code.
  • Finally, it should allow explicit conversion from an enumerator to error_code or error_condition. Portable programs may need to create error codes that are derived from the std::errc::* enumerators.

So, while it's true that the line:

if (ec == std::errc::file_exists)

implicitly converts from errc to error_condition, there are a few more steps involved.

Step 1: determine whether the enum is an error code or condition

Two type traits are used to register enum types with the facility:

template <class T>
struct is_error_code_enum
: public false_type {};

template <class T>
struct is_error_condition_enum
: public false_type {};

If a type is registered using is_error_code_enum<> then it may be implicitly converted to an error_code. Similarly, if a type is registered using is_error_condition_enum<>, it can be implicitly converted to error_condition. By default, types are registered for neither conversion (hence the use of false_type above), but enum class errc is registered as follows:

template <>
struct is_error_condition_enum<errc>
: true_type {};

The implicit conversion is accomplished by conditionally enabled conversion constructors. This is probably implemented using SFINAE, but for simplicity you need only think of it as:

class error_condition
{
...
// Only available if registered
// using is_error_condition_enum<>.
template <class ErrorConditionEnum>
error_condition(ErrorConditionEnum e);
...
};

class error_code
{
...
// Only available if registered
// using is_error_code_enum<>.
template <class ErrorCodeEnum>
error_code(ErrorCodeEnum e);
...
};

Therefore, when we write:

if (ec == std::errc::file_exists)

the compiler has to choose between these two overloads:

bool operator==(
const error_code& a,
const error_code& b);

bool operator==(
const error_code& a,
const error_condition& b);

It chooses the latter because the error_condition conversion constructor is available, but the error_code one is not.

Step 2: associate the value with an error category

An error_condition object contains two attributes: value and category. Now that we're in the constructor, these need to be initialised correctly.

This is accomplished by having the constructor call the function make_error_condition(). To enable user-extensibility, this function is located using argument-dependent lookup. Of course, since errc is in namespace std, its make_error_condition() is found there too.

The implementation of make_error_condition() is simply:

error_condition make_error_condition(errc e)
{
return error_condition(
static_cast<int>(e),
generic_category());
}

As you can see, this function uses the two-argument error_condition constructor to explicitly specify both the error value and category.

If we were in the error_code conversion constructor (for an appropriately registered enum type), the function called would be make_error_code(). In other respects, the construction of error_code and error_condition is the same.

Explicit conversion to error_code or error_condition

Although error_code is primarily intended for use with OS-specific errors, portable code may want to construct an error_code from an errc enumerator. For this reason, both make_error_code(errc) and make_error_condition(errc) are provided. Portable code can use these as follows:

void do_foo(std::error_code& ec)
{
#if defined(_WIN32)
// Windows implementation ...
#elif defined(linux)
// Linux implementation ...
#else
// do_foo not supported on this platform
ec = make_error_code(std::errc::not_supported);
#endif
}

Some history

The original <system_error> proposal defined error_code constants as objects:

extern error_code address_family_not_supported;
extern error_code address_in_use;
...
extern error_code value_too_large;
extern error_code wrong_protocol_type;

The LWG was concerned about the size overhead of so many global objects, and an alternative approach was requested. We researched the possibility of using constexpr, but that was ultimately found to be incompatible with some other aspects of the <system_error> facility. This left conversion from enum as the best available design.

Next, I'll start showing how you can extend the facility to add your own error codes and conditions.

40 comments:

Anne said...

This would be great if it were used in boost::asio! Unfortunately, it does not appear to be. From boost/asio/error.hpp:


template<> struct is_error_code_enum<boost::asio::error::basic_errors>
{
static const bool value = true;
};


I can't find a set of error conditions I can use for asio errors; just error codes.

Anonymous said...

In Part-3, the paragraph: "Obviously, this is because there's an implicit conversion from errc to error_condition using a single-argument constructor. Simple. Right?"

Should not say "because there's an implicit conversion from errc to error_code" instead?

Anonymous said...

I don't think so, recall that a single error_condition can map to several error_codes, and since there is a one-to-one mapping between error_conditions and errc enumerators, an error_condition cannot be converted to a single error_code.

Siva said...

I’m impressed with the post which you have shared. This is very informative to know the benefits of outsourcing web development services.
Hire Dedicated Laravel Developer
Hire Phonegap Developer
Hire Cake Php Developer
Hire Dedicated Developers
Dedicated Magento Developer

Gryffin said...

Also, wanted to know the Enums inside of a C++ class. click

Lorriel Sims said...

configuration and troubleshooting for a wide range of home electronics including televisions in www.floorrefinishingstlouis.com/

Jylia said...

paper writing service review perform a terrific job. It's a rare thing nowadays to collect honest business reviews. This website assists hundreds of students to locate every day a correct honest writer.

Dim4ksan said...

When you meet a Moldovan girl initially you notice her inherent attractiveness. moldova brides don't desire to seem affluent, unlike Russian fashion and luxury businesses that adore Russia. Their distinctive design enables them to accentuate their inherent attractiveness without loud markings and branding on their clothing. You purchase clothing and shoes, and you don't care about the makers. In addition, the Moldovan brides are not spending much on cosmetics. The Chanel or Dior lipstick simply does not give them a natural, bright look. If you want to meet a gorgeous Moldovan bride, then head to the Moldovan Brides.

kalamena said...

Only a few years ago it was difficult to find a woman on the Internet. The Internet is now worldwide availability. Women have already created and searched for their own accounts. Here you may feel certain that each women on this site is real. The questionnaire may be completed, tested and searched conveniently. The webpage is really simple. There's a legit mail order bride, too.

Dim4ksan said...

By turning to https://myexamcoach.com/ I successfully passed my exams. I hired a personal trainer at a very reasonable price. I prepared for my exams in just one week and passed everything with flying colors. I advise you to refer to this site as I consider it to be the best site for exam preparation. I wish everyone to pass the exam successfully.

ASAP DEMO said...

Are you in forex trading? It is one of the most popular and profitable financial markets in the world. Visit my site to find more info about most traded currencies on forex market.

emmynika said...

Thank you for sharing this amazing information blog, its absolutely exceptional, well written and with fascinating article contents. I found so much joy reading through and I hope for more of such useful though as I bookmarked the page. ksu cut off mark for computer science

shopify said...

Top Notch Experts for A Grade Assignments High Calibre can i pay do my homework for me adept with all forms of writing styles

배트맨토토 said...

What's up friends, how is the whole thing, and what you want to say on the topic of this post,
in my view its truly remarkable for me.



스포츠토토티비
스포츠중계

배트맨토토 said...

Thanks for sharing your info. I really appreciate your efforts and I will be waiting for your further write.
Thanks for sharing !



토토365프로
스포츠토토

visa to Kenya from UK said...

Nice post. Thank you for this work. The travelers need to apply visa to Kenya from UK through online visa application. Check the details and read the guidelines before you fill up the application form.

Dijital Pazarlamacilar said...


Reklam stratejinizi değiştirmek için ihtiyaç duyacağınız en iyi gerilla pazarlama fikirlerine hoş geldiniz, pazarlama öğrencileri !

Baskınların ve pusuların görüntülerini bir araya getirdiyseniz, sizi (özellikle tüm Call of Duty hayranları) hayal kırıklığına uğrattığım için üzgünüm.

Gerilla pazarlaması savaşmak değildir. Sürpriz unsurunu kullanarak birini kazanmakla ilgili!

O halde, piyasadaki en iyi gerilla pazarlama fikirlerinden biraz ilham alalım!

Gerilla Pazarlama Nedir

Gerilla pazarlamasının tanımı, büyük ölçüde “gerilla savaşı” (“gerilla” olarak da yazılır) tanımına dayanır.

Gerilla, daha büyük, daha organize bir güçle savaşan, gevşek bir şekilde organize edilmiş, taktiksel olmayan bir orduyu ifade eder. Sizin için bu “daha ​​büyük organize güç”, kendilerini pazarda kurmuş büyük bütçeli rakiplerdir.

Yani…

Gerilla Pazarlama Nedir?
Gerilla pazarlama, tipik olarak maliyetinin çok altında bir pazarlama kampanyası başlatmak için kullanılan bir dizi pazarlama eylemidir .

Etki, elbette, buna yatırılan düşük bütçeden bağımsız olarak daha önemli olmalıdır. Başka bir deyişle, gerilla pazarlama, bir pazarlama kampanyasının etkisi için bir büyüteç görevi görür.

Benim ifademle gerilla pazarlaması, pazarlamanın Banksy tarafı gibidir. Elbette daha ucuz olması, gerilla pazarlama kampanyanızın zaman kaybı olacağı anlamına gelmiyor!

Mesajınızı iletmek için ister bir çıkartma ister bir şablon kullanın, her şey hedef kitlenizi ne kadar şaşırttığına bağlıdır. Ne kadar sıra dışı olursa, hedef kitlenizin gözünde o kadar çarpıcı olacaktır.

Bazen sevgili gerilla pazarlamacılarım, süslü olmanıza bile gerek yok. Öyleyse söyle bana, Frontline'ın aşağıdaki reklamında ne görüyorsun ?

gerilla pazarlama fikirleri

İpucu: bunlar pire değil. Onlar gerçek insanlar!

Neyi kastettiğimi anla?

En İyi Gerilla Pazarlama Fikirleri Türleri
Bu sözde “gerilla pazarlama türleri”nin var olup olmadığını bulmak için oldukça fazla araştırma yaptım. Bu türlerin hiçbirini bilimsel bir makale altında bulamamış olsam da, anlaşılır olması açısından sunacağım.

İşte en önemli parçaların bir karışımı:

Sokak Pazarlama
Sokak pazarlaması, açık hava gerilla pazarlama türü için daha yakın zamanda ortaya atılan bir terimdir . Sokak unsurlarını devreye sokan, açık havada gerçekleşen tüm pazarlama eylemlerini ifade eder.

En başarılı sokak pazarlama kampanyalarından bazıları, bir açıklama yapmak için sokak sanatını kullanır. McDonald's'ın bu akıllı gerilla pazarlama fikrine bir göz atın :

expedited Indian visa said...

This article is very informative... Thanks for sharing with us...please continue... An expedited Indian visa is available at most foreign consulates, for those who plan to travel abroad within a couple of weeks or less, for more information just click and check it.

Anonymous said...

faststone capture crack
ableton live crack

Victor said...

Amazing . I think you are a professional blogger. I feel very positive after reading your post. .What is the Vietnam Visa processing time? A Vietnam evisa is easily approved within 3 -5 business days.

Richard said...

Many thanks .I feel better in the wake of perusing your article. I really want to believe that you will proceed. Write this sort of article for us. Might it be said that you are pondering the India visa? The Government of India has worked on the India Visa Application procedure.so don't hold back about the india visa.

Anonymous said...

What a very informative site, thank you for sharing!
Excavating contractors

카지노정보 said...

type in the numbers and letters they see 카지노사이트

Judie Andreozzi said...

Executive-Education.id is often a provider of personal teaching education expert services where by a person coach solely demonstrates to one-three pupils plus helping plus understanding things to do ... visit https://kursus-akuntansi.netlify.app/kursus-akuntansi-setiabudi.html for further

casinositetop said...

Magnificent as ever, More post pleased! Thanks
카지노사이트위키
바카라사이트
카지노사이트
온라인카지노
카지노사이트

Johnson said...

Do you need the best free movies download websites where you can get the best hollywood movies? Check this out... It includes Bollywood too.

Jeanie Caporale said...

Jabodetabek private tutoring services with teachers coming to the house. Over many hundreds of active tutors will be ready teach various skills and lessons of the to adults ... click https://kursus-mandarin.vercel.app/kursus-bahasa-mandarin-cakung.html for more information

Anonymous said...

I am so grateful to have found this post. It is so well-explained. Residential Insulation Services

Anonymous said...

I want to save this content! Thank you best water softener

cégeladás menete said...

I liked this article. It was inspiring. Please keep on posting.

Majortotosite Top said...

This is a wonderful news regarding bloggers.

Oncasinosite Net said...

Thanks just for this informative publish, I learned a whole lot!

Totopick Pro said...

After study few of the articles on your web site today, and I really like your way of blogging.

Totosafeguide Com said...

I tag it to my bookmark internet site list and will be checking back soon.

működő eladó cégek adequit said...

This is an interesting insight into the topic, thanks.

Anonymous said...

Glad to visit this site, nice content indeed. St. Louis Concreters St. Louis Missouri

RyeD said...


Glad to visit this site. Great work! concrete driveway

sms onay said...

sms onay

Steven Markup said...

This is the most beneficial post for me, it is defining properly and carefully the concept and the flow of content, that's amazing. Thanks for sharing this helpful post with us. 49ers super bowl jacket

Reliable plumber said...


Such a pretty cool site. This is a really great guide for me!