C++ trick: selectively restrict implicit conversions

TL;DR: given a class Foo with an implicit constructor from int, how to allow the implicit conversion in f(42); but not in g(42); where both f and g take a Foo const & argument?

Background

So I have this real class that performs numeric operations that I want use just like any other C++ numeric type. For instance, I can write the following:

float f = 15, g = 3.5;
int x = f / g;

If I decide that I need double precision, I can write:

double f = 15, g = 3.5;
int x = f / g;

And of course, using my real class for even higher precision:

real f = 15, g = 3.5;
int x = f / g;

I like that. I can just write code as usual, and when I need higher precision, I use real instead of double. It's transparent and convenient.

Implementation example

Here is a highly simplified example of a real class:

struct real
{
    inline real(double d) : m_value(d) {}
    inline operator int() const { return (int)m_value; }
    /* ... */
    long double m_value;
};

It is possible to write real f = 15 because of the implicit constructor. Actually, C++ constructors are always implicit unless specified otherwise.

It is possible to write int x = f / g because of the conversion operator.

So far, so good.

The problem with implicit promotion

Here is how fabs could be implemented:

real fabs(real const &r)
{
    return real(r.m_value < 0 ? -r.m_value : r.m_value);
}

But now we have a problem. A subtle problem. Consider the following code:

double x = fabs(-5.0);

What does this do? Well, it depends. It depends whether <cmath> was included or not. Because if <cmath> wasn’t included, then that code is going to automatically promote -5.0 to a real and call our custom function instead of the one provided by the math library! With no compile-time warning!

This is confusing. It should not happen. But it is a well known problem and there are several obvious workarounds:

  1. What most professional C++ programmers will tell you: use namespaces
  2. Mark the real(int) constructor explicit

The problem with 1. is that I am not a professional C++ programmer. I am a C programmer who uses C++. I use preprocessor macros and printf and memalign and goto. Try and stop me!

The problem with 2. is that I can no longer write real f = 15, I would need real f(15) or real f = real(15) instead. This is not acceptable, I want real to behave exactly like float and others, to the fullest extent of what the language allows.

Another solution

Fortunately, the C++ standard has a solution for us: “Implicit conversions will be performed [...] if the parameter type contains no template-parameters that participate in template argument deduction” (ISO/IEC 14882:1998, section 14.8.1.4). You cannot have implicit conversion and template argument deduction at the same time.

It means we just have to make fabs a template function! Which means making real a template class, too.

A quick way to fix real would be:

/* N is unused */
template<int N> struct real_base
{
    inline real_base(double d) : m_value(d) {}
    inline operator int() const { return (int)m_value; }
    /* ... */
    long double m_value;
};

typedef real_base<0> real;

The template argument is useless, unfortunately. It will just have to be here, forever. But who knows, you might find a use for it one day.

And to fix fabs:

/* A generic template declaration is needed */
template<int N> real_base<N> fabs(real_base<N> const &r);

/* Here we just add template<> to the previous version */
template<>
real fabs(real const &r)
{
    return real(r.m_value < 0 ? -r.m_value : r.m_value);
}

So, what happens with double x = fabs(-5.0); when we forget to include <cmath> now? Well, here is what GCC says:

In function ‘int main()’:
error: no matching function for call to ‘fabs(double)’
note: candidate is:
note: template<int N> real_base<N> fabs(const real_base<N>&)

It seems we’ve successfully managed to avoid the problematic implicit conversion, yet still allow it in places where it was useful!

So what is the rule? It’s simple: where implicit conversion should not be allowed, make the function a specialised template function.

  • Posted: 2012-02-08 22:14 (Updated: 2012-02-09 00:31)
  • Author: sam
  • Categories: code tip c++

Comments

158. MelbaJoulp -- 2017-01-13 07:10
159. MeghanCon -- 2017-01-13 20:47

get healthy life essay free example cover letters for resume gender discrimination in malaysia essay http://www.tukaerusite.com/j?u=http%3A%2F%2Fkayble.us

160. Angelavep -- 2017-01-13 22:16

You always do the right thing. God Bless you. Thank you

161. SusanArrix -- 2017-01-15 22:28

gcse maths statistics coursework help free restaurant resume examples

162. Helennut -- 2017-01-15 22:28

formal guidelines to writing a research paper essay writer co uk reviews

163. Helennut -- 2017-01-16 08:28

free youtube video downloader with resume free gcse french coursework

164. SusanArrix -- 2017-01-16 08:28

fallacy essay essay writing language techniques

167. Laurapails -- 2017-01-16 19:41

euthanasia essay assisted suicide should not be legal excent for university coursework http://win61.ru/go.php?go=http://shelfhelp.xyz

168. Juliedix -- 2017-01-17 04:58

food distributors business plan good ideas for english research papers http://autoadmit.com/go.php?url=http%3A%2F%2Fkovrick.us

170. Juliedix -- 2017-01-17 09:22

good and bad communication essay facebook popularity essay http://femdom.kinkest.com/cgi-bin/out.cgi?ses=xnhS7N6rbt&id=422&url=http://kaydoo.us

171. SarahOrent -- 2017-01-17 09:22

example of cover letter for government of canada free essay on stem cell research http://www.thassos-forum.com/go.php?to=http%3A//guliguli.us

176. ParisHiesy -- 2017-01-18 21:40

free resume manager free ap biology lab homework help exegetical essay essay writing made easy body paragraphs free recruiters resume search http://divavee.us

177. DonaldSem -- 2017-01-19 07:47

герпес на спине как избавиться http://ercancinar.xyz/index.php?viewurl=14135 воспаление простаты от камней в почках

178. DonaldSem -- 2017-01-19 07:47

чем можно вывести бородавку на руке в домашних условиях http://prettyfuckingawesome.xyz/index.php?link=1702 интернет аптека пиперазин цена

182. DonaldSem -- 2017-01-19 11:53

когда лучше удалять папилломы летом или зимой http://dubo188.xyz/index.php?viewurl=6111 увеит черные точки

183. DonaldSem -- 2017-01-19 11:53

эффективный заговор чтобы родственник бросил пить http://kartina-gobelen.ru/index.php?page-id=2191 единичное количество лейкоцитов в соке простаты

193. Clintonnib -- 2017-01-27 02:02

Сироп мангустина растопит до 10 кг жира за 2 недели! Спаситесь от ожирения и сократите риск инфаркта, диабета и гипертонии на 89%. Перейти на сайт: http://mangoo77.mangoosteen.com/

322. whvpywcq -- 2017-07-22 09:40

zq1hky05egraoxmoly <a href="https://bybklfn.info/">order baclofen</a> <a href=https://bybklfn.info/>buy generic baclofen</a> mdxv9kl7ds32bp2kpn

323. whvpywcq -- 2017-07-22 09:40

zq1hky05egraoxmoly <a href="https://bybklfn.info/">order baclofen</a> <a href=https://bybklfn.info/>buy generic baclofen</a> mdxv9kl7ds32bp2kpn

324. whvpywcq -- 2017-07-22 09:40

zq1hky05egraoxmoly <a href="https://bybklfn.info/">order baclofen</a> <a href=https://bybklfn.info/>buy generic baclofen</a> mdxv9kl7ds32bp2kpn

325. whvpywcq -- 2017-07-22 09:40

zq1hky05egraoxmoly <a href="https://bybklfn.info/">order baclofen</a> <a href=https://bybklfn.info/>buy generic baclofen</a> mdxv9kl7ds32bp2kpn

326. whvpywcq -- 2017-07-22 09:40

zq1hky05egraoxmoly <a href="https://bybklfn.info/">order baclofen</a> <a href=https://bybklfn.info/>buy generic baclofen</a> mdxv9kl7ds32bp2kpn

327. whvpywcq -- 2017-07-22 09:40

zq1hky05egraoxmoly <a href="https://bybklfn.info/">order baclofen</a> <a href=https://bybklfn.info/>buy generic baclofen</a> mdxv9kl7ds32bp2kpn

328. whvpywcq -- 2017-07-22 09:40

zq1hky05egraoxmoly <a href="https://bybklfn.info/">order baclofen</a> <a href=https://bybklfn.info/>buy generic baclofen</a> mdxv9kl7ds32bp2kpn

329. whvpywcq -- 2017-07-22 09:40

zq1hky05egraoxmoly <a href="https://bybklfn.info/">order baclofen</a> <a href=https://bybklfn.info/>buy generic baclofen</a> mdxv9kl7ds32bp2kpn

330. whvpywcq -- 2017-07-22 09:40

zq1hky05egraoxmoly <a href="https://bybklfn.info/">order baclofen</a> <a href=https://bybklfn.info/>buy generic baclofen</a> mdxv9kl7ds32bp2kpn

331. whvpywcq -- 2017-07-22 09:40

zq1hky05egraoxmoly <a href="https://bybklfn.info/">order baclofen</a> <a href=https://bybklfn.info/>buy generic baclofen</a> mdxv9kl7ds32bp2kpn

332. whvpywcq -- 2017-07-22 09:40

zq1hky05egraoxmoly <a href="https://bybklfn.info/">order baclofen</a> <a href=https://bybklfn.info/>buy generic baclofen</a> mdxv9kl7ds32bp2kpn

333. heaaymoc -- 2017-07-22 21:50

sr171v4bgb6jbjwj2p <a href="https://bybklfn.info/">buy generic baclofen</a> <a href=https://bybklfn.info/>baclofen online</a> 85vppssrksr25bimut

334. heaaymoc -- 2017-07-22 21:50

sr171v4bgb6jbjwj2p <a href="https://bybklfn.info/">buy generic baclofen</a> <a href=https://bybklfn.info/>baclofen online</a> 85vppssrksr25bimut

335. heaaymoc -- 2017-07-22 21:50

sr171v4bgb6jbjwj2p <a href="https://bybklfn.info/">buy generic baclofen</a> <a href=https://bybklfn.info/>baclofen online</a> 85vppssrksr25bimut

339. zd2yfr1n -- 2017-07-30 16:26

The serum concentration of Prednisone can be increased when it is combined with Sertraline. <a href=https://byprdnsn.info/>prednisone online</a>, steroid injection for urticaria - steroid injection for urticaria:

340. zd2yfr1n -- 2017-07-30 16:26

The serum concentration of Prednisone can be increased when it is combined with Sertraline. <a href=https://byprdnsn.info/>prednisone online</a>, steroid injection for urticaria - steroid injection for urticaria:

341. zd2yfr1n -- 2017-07-30 16:26

The serum concentration of Prednisone can be increased when it is combined with Sertraline. <a href=https://byprdnsn.info/>prednisone online</a>, steroid injection for urticaria - steroid injection for urticaria:

342. zd2yfr1n -- 2017-07-30 16:26

The serum concentration of Prednisone can be increased when it is combined with Sertraline. <a href=https://byprdnsn.info/>prednisone online</a>, steroid injection for urticaria - steroid injection for urticaria:

343. zd2yfr1n -- 2017-07-30 16:26

The serum concentration of Prednisone can be increased when it is combined with Sertraline. <a href=https://byprdnsn.info/>prednisone online</a>, steroid injection for urticaria - steroid injection for urticaria:

344. zd2yfr1n -- 2017-07-30 16:26

The serum concentration of Prednisone can be increased when it is combined with Sertraline. <a href=https://byprdnsn.info/>prednisone online</a>, steroid injection for urticaria - steroid injection for urticaria:

345. zd2yfr1n -- 2017-07-30 16:26

The serum concentration of Prednisone can be increased when it is combined with Sertraline. <a href=https://byprdnsn.info/>prednisone online</a>, steroid injection for urticaria - steroid injection for urticaria:

346. zd2yfr1n -- 2017-07-30 16:26

The serum concentration of Prednisone can be increased when it is combined with Sertraline. <a href=https://byprdnsn.info/>prednisone online</a>, steroid injection for urticaria - steroid injection for urticaria:

349. k05k5l9r -- 2017-07-31 08:11

Do not flush medications down the toilet or pour them into a drain unless instructed to do so. <a href=https://byprdnsn.info/>order prednisone</a>, prednisone dose for itchy dog

350. k05k5l9r -- 2017-07-31 08:11

Do not flush medications down the toilet or pour them into a drain unless instructed to do so. <a href=https://byprdnsn.info/>order prednisone</a>, prednisone dose for itchy dog

351. k05k5l9r -- 2017-07-31 08:11

Do not flush medications down the toilet or pour them into a drain unless instructed to do so. <a href=https://byprdnsn.info/>order prednisone</a>, prednisone dose for itchy dog

352. k05k5l9r -- 2017-07-31 08:11

Do not flush medications down the toilet or pour them into a drain unless instructed to do so. <a href=https://byprdnsn.info/>order prednisone</a>, prednisone dose for itchy dog

353. k05k5l9r -- 2017-07-31 08:11

Do not flush medications down the toilet or pour them into a drain unless instructed to do so. <a href=https://byprdnsn.info/>order prednisone</a>, prednisone dose for itchy dog

354. k05k5l9r -- 2017-07-31 08:12

Do not flush medications down the toilet or pour them into a drain unless instructed to do so. <a href=https://byprdnsn.info/>order prednisone</a>, prednisone dose for itchy dog

355. k05k5l9r -- 2017-07-31 08:12

Do not flush medications down the toilet or pour them into a drain unless instructed to do so. <a href=https://byprdnsn.info/>order prednisone</a>, prednisone dose for itchy dog

356. k05k5l9r -- 2017-07-31 08:12

Do not flush medications down the toilet or pour them into a drain unless instructed to do so. <a href=https://byprdnsn.info/>order prednisone</a>, prednisone dose for itchy dog

357. farhan@balanc3r.com -- 2018-07-11 09:13

Your music is amazing. You have some very talented artists. I wish you the best of success. Auto https://pkws.net/

358. anonymous -- 2018-07-30 10:06

I have read your blog it is very helpful for me. I want to say thanks to you. I have bookmark your site for future updates. pdf https://un-curso-en-milagros.org/

359. anonymous -- 2018-07-30 16:30

Its a great pleasure reading your post.Its full of information I am looking for and I love to post a comment that "The content of your post is awesome" Great work. a course in miracles https://acim.biz/

360. anonymous -- 2018-07-31 10:23

You completed a few fine points there. I did a search on the subject and found nearly all persons will go along with with your blog. advaita teachers http://www.nonduality.xyz/

361. anonymous -- 2018-08-01 14:26

This is a good post. This post gives truly quality information. I’m definitely going to look into it. Really very useful tips are provided here. Thank you so much. Keep up the good works. Cinder Cone Clay Center http://www.cinderconeclaycenter.com

362. anonymous -- 2018-08-02 09:38

Good article, but it would be better if in future you can share more about this subject. Keep posting. Vertex Central http://vertexcentral.residences.ph/

363. anonymous -- 2018-08-02 09:38

Good article, but it would be better if in future you can share more about this subject. Keep posting. Vertex Central http://vertexcentral.residences.ph/

364. anonymous -- 2018-08-07 17:19

Great Information sharing .. I am very happy to read this article .. thanks for giving us go through info.Fantastic nice. I appreciate this post. suzuki coin https://suzukicoin.net/

365. Case Study Writing Services -- 2018-09-11 12:23

Thanx for sharing such useful post keep it up :) https://caseanswers.xyz

366. Coursework Homework Help -- 2018-09-11 13:43

by visiting this site I found cool stuff here keep it up. https://www.courseworkhelponline.xyz/

367. assignmentprofs@gmail.com -- 2018-09-22 08:09

A very genuine post which points out a hidden erroer which most of the times our developers aren't able to spot.Assignment Profs Expert Service

368. anonymous -- 2018-10-07 06:39

I really like what you guys are usually up too. This sort of clever work and exposure! Keep up the superb works guys I've incorporated you guys to my blogroll. (run 3):https://run3cool.io/

369. Content Writing Agency -- 2018-10-12 12:05

We Also Share Some Information About Our Business https://www.contentastic.com/

370. C Sharp Project Help Online -- 2018-10-12 13:02

Thanx For Sharing Such Useful Post Keep It Up :) https://csharpaid.com

371. anonymous -- 2018-10-15 14:05

Nice to read your article! I am looking forward to sharing your adventures and experiences. Enjoy Mexico top desinations https://enjoymexico.net/top-mexico-destinations/

372. anonymous -- 2018-10-16 10:12

This is such a great resource that you are providing and you give it away for free. I love seeing websites that understand the value of providing a quality resource for free. It is the old what goes around comes around routine. Enjoy Mexico Villa Rentals in Punta Mita https://enjoymexico.net/punta-mita-villa-rentals/

373. anonymous -- 2018-10-17 10:30

I can see that you are an expert at your field! I am launching a website soon, and your information will be very useful for me.. Thanks for all your help and wishing you all the success in your business. Enjoy Mexico Villa Rentals in Cabo San Lucas https://enjoymexico.net/villa-rentals-cabo-san-lucas/

374. anonymous -- 2018-10-18 09:14

I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post. iphoneattunlock http://www.iphoneattunlock.com/

375. anonymous -- 2018-10-20 14:13

This blog is so nice to me. I will keep on coming here again and again. Visit my link as well.. The Hyde condo https://thehydeofficial.livejournal.com/

376. anonymous -- 2018-11-05 11:19

I admit, I have not been on this web page in a long time... however it was another joy to see It is such an important topic and ignored by so many, even professionals. professionals. I thank you to help making people more aware of possible issues. Nicole Bray https://www.nicolebrayrealestate.com

377. shanjasper -- 2018-11-05 19:02

Thanks for your post! It’s been a long time since I read a good article and such a meaning! I hope you will continue to write articles like these for hobbyists! https://www.theacademicpapers.co.uk/assignment-writing-services-uk.php

378. anonymous -- 2018-11-08 12:45

i read a lot of stuff and i found that the way of writing to clearifing that exactly want to say was very good so i am impressed and ilike to come again in future.. Home Health Care Boca Raton http://homehealthcarebocaraton.com

379. anonymous -- 2018-11-12 11:03

Thanks for the post and great tips..even I also think that hard work is the most important aspect of getting success.. Bücher für plastische Chirurgie https://www.books-plastic-surgery.com/

380. anonymous -- 2018-11-13 11:16

I admit, I have not been on this web page in a long time... however it was another joy to see It is such an important topic and ignored by so many, even professionals. professionals. I thank you to help making people more aware of possible issues. Nachrichten https://wirtschaft.com/fernsehen

381. anonymous -- 2018-11-26 11:24

thanks for this usefull article, waiting for this article like this again. click here http://nwnjpeace.org/

382. anonymous -- 2018-11-27 08:24

Thanks for sharing us. click this site http://www.floridabusinessbroker.org/

383. anonymous -- 2018-11-29 06:50

I have bookmarked your blog, the articles are way better than other similar blogs.. thanks for a great blog! JB Records http://www.jbirdrecords.com/

384. annashetty -- 2018-12-03 08:54

I am grateful to have opened this discussion. This question is quite interesting to me. Finally the answer was found run 3 cool math

385. anonymous -- 2018-12-06 10:46

These are some great tools that i definitely use for SEO work. This is a great list to use in the future.. Louisville Attorney http://mylouisvilleattorney.com/

386. anonymous -- 2018-12-08 10:33

This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here! keep up the good work Max Beltoon https://www.maxbeltoon.com/

387. anonymous -- 2018-12-09 10:56

I read your blog frequently and I just thought I’d say keep up the amazing work! Ichbin Christ http://www.ichbinchrist.net/

388. anonymous -- 2018-12-10 11:48

I read that Post and got it fine and informative. Please share more like that... Explore Capitola http://www.explorecapitola.com/

Add New Comment