Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do C++ function templates encourage weaker typing?

Tags:

c++

I started learning C++ by reading Accelerated C++ practical programming by example and got stuck on function templates. I understand what they do... and why they might be useful at times. But I also find them a bit inelegant and even confusing for the caller, let me explain.

The book first defines a function:

vector<string> split(string& s) which maps "hello world" to a vector with entries hello and word.

Then, the author claims that we can make our function more flexible and let the caller choose a different container (a list instead of a vector for example) and for this, they propose the following:

template <class Out> void split(const string& str, Out os)

My questions are,

  1. How do I know... as a caller that Out must be an iterator? it could literally be anything.

  2. If I somehow figure out it takes an iterator, I still don't know which kind.. input output forward sequential etc.

To figure these things out I would need to take a look into the function and see what operators are used in the iterator (++,>,=). As a "user" of the function I should care about what it does... not how it does it.

Function templates seem to encourage a weaker form of typing. While writing this, I realized that this question might have little to do with C++ and more to do with my inexperience using weaker typed languages, but I'll let you be the judge of that.

like image 925
frankelot Avatar asked Mar 22 '26 13:03

frankelot


1 Answers

How do I know... as a caller that Out must be an iterator? it could technically be anything!

That's the question to the documentation or the author of code. Good template functions verify if type provided meets expectations. It can be done e.g. by a couple of static_asserts to ensure Out meets expectations. Standard library <type_traits> offers a number of tests, which can be performed on types to check them.
Or you could just name the template parameter a bit more verbosely:

template <class OutputIterator> void split(const string& str, OutputIterator os)

Now noone should have any doubt what type is expected.

Template functions seem to encourage dynamic typing.

There is no dynamic typing in C++. All template parameters are resolved at compile time. Compiler knows perfectly well what type is Out when it compiles each call to split.

If I somehow figure out it takes an iterator, I still don't know which kind.. input output forward sequential etc.

Again, this is the question to the author/documentation. If you write such a function, it's best to make sure the template type is what you expect with static_assert, however testing existence of operator overloads might be difficult.

like image 167
Yksisarvinen Avatar answered Mar 25 '26 02:03

Yksisarvinen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!