Search⌘ K

Discussion: A Specialized String Theory

Explore how overload resolution works with function templates and specializations in C++. Learn to distinguish between primary templates, explicit specializations, and non-template overloads through detailed examples involving serialization functions. Understand how template argument deduction affects which function is called, and gain practical advice for managing template-based code effectively.

Run the code

Now, it’s time to execute the code and observe the output.

C++ 17
#include <iostream>
template<typename T>
void serialize(T&) { std::cout << "template\n"; } // 1
template<>
void serialize<>(const std::string&) { std::cout << "specialization\n"; } // 2
void serialize(const std::string&) { std::cout << "normal function\n"; } // 3
int main()
{
std::string hello_world{"Hello, world!"};
serialize(hello_world);
serialize(std::string{"Good bye, world!"});
}

Understanding the output

Remember our serialization library from the String Theory puzzle? In the meantime, a C++ expert has come along and decided that everything is better with templates. Whether or not that’s true is another discussion, but it certainly makes overload resolution more interesting!

We find three definitions of serialize in the above code puzzle:

  • Line 4: This is the primary function template for serialize().

  • Line 7: This is an explicit specialization of this template for std::string. We can recognize it as a specialization by the empty template<> tag.

  • Line 9: Finally, we see a plain old non-template serialize function. ...

Function template and overload resolution