this post was submitted on 15 Nov 2023
12 points (100.0% liked)

C++

1732 readers
1 users here now

The center for all discussion and news regarding C++.

Rules

founded 1 year ago
MODERATORS
 

C++ trick I pulled today. Like an explicit constructor but context dependent. Any alternatives from folks who've needed to do similar? One thing I still need to dig into a little deeper is how copy elision behaves here.

you are viewing a single comment's thread
view the rest of the comments
[–] [email protected] 5 points 1 year ago (4 children)

It's an interesting little gotcha, but I wonder if it wouldn't be preferable to just implement a type trait like is_expensive_conversion that is false by default and true for specific cases, and just static_assert this stuff.

Relying on obscure implicit type conversion mechanics for this feature feels like being too clever for your own good.

[–] [email protected] 2 points 1 year ago* (last edited 1 year ago) (3 children)

That's a fair criticism around relying on implicit type conversion mechanics, and part of the tradeoff to make. On the other hand, I imagine (and my imagination may be limited) that one downside of static_assert is to increase verbosity, something like:

auto r = f();
static_assert(std::is_same_v<decltype(r),MyReturnType>> || !is_expensive_conversion_v<MyReturnType>);
return r;
[–] golvok 1 points 11 months ago (1 children)

I'm wondering where you wanted to use this. Was it a generic context, where you didn't know what types you were getting? Also, I think it will interfere with the retern-value optimization.

[–] [email protected] 2 points 11 months ago* (last edited 11 months ago) (1 children)

Yes, that's right, generic context, and you may be right on return value optimization. It was for implementing a collection of numerical functions that take array arguments, where the elements of those arrays could be of various arithmetic types, and the return type should be an array of a particular arithmetic type given promotion etc. The implementation was generic, and I was wanting to validate its correctness wrt return values having the correct arithmetic type without implicit copy.

[–] [email protected] 2 points 11 months ago

For the array type it can be useful to allow implicit copy to different arithmetic types (design choice, I'm now back to explicit constructors to disallow this for what it's worth). If allowed though, I still wanted a compile time check like this to ensure that it wasn't happening by accident in particular circumstances.

load more comments (1 replies)
load more comments (1 replies)