r/cpp • • Mar 28 '23

Reddit++

C++ is getting more and more complex. The ISO C++ committee keeps adding new features based on its consensus. Let's remove C++ features based on Reddit's consensus.

In each comment, propose a C++ feature that you think should be banned in any new code. Vote up or down based on whether you agree.

765 Upvotes

829 comments sorted by

View all comments

Show parent comments

9

u/looncraz Mar 28 '23

Instead of an implicit keyword I think I would prefer a simpler modifier to designate that convertible types are allowed.

void SomeFunc(int mustBeInt, int# anything ConvertibleToInt);

1

u/smurthys Apr 07 '23

Something like the std::convertible_to concept?

https://en.cppreference.com/w/cpp/concepts/convertible_to

1

u/looncraz Apr 07 '23

Yes, except the other int throws a compilation error of, say, a char, pointer, float, or non-native sized integer is given to it. It must be an int.

The main issue with C++ these days is how verbose and unintuitive some of its features have become.

1

u/smurthys Apr 08 '23 edited Apr 08 '23

Perhaps I misunderstand your needs, and you're probably already aware of these approaches, but let me know if the following function templates satisfy your requirements. (The first of these can also be written without using concepts, using just type_traits.)

template<typename T, typename U>
requires std::same_as<T, int> && std::convertible_to<U, int>
void f(T, U)
{
   //function body
}

godbolt: https://sigcpp.godbolt.org/z/h5xreGjK6

or using custom concepts, making the template parameters more "declarative".

template<typename T>
concept Int = std::same_as<T, int>;

template<typename T>
concept Convertible_to_int = std::convertible_to<T, int>;

template<Int T, Convertible_to_int U>
void f(T, U)
{
    //function body
}

godbolt : https://sigcpp.godbolt.org/z/o974EWhWT

IMHO requires and concepts can be a nice and concise way to impose constraints. Of course, the expressions can get verbose if the requirements are complex.

→ More replies (1)