Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele Working with Multiple Typenames in Templates | Creating First Template
C++ Templates

book
Working with Multiple Typenames in Templates

Sometimes you will need more than one type to use in the function, and for this you can simply add more template parameters. Just make sure you give them different names.

Note

There is no inherent limit to the number of template parameters. However, as a general guideline keep the number of them as low as possible.

Create the function template print_pair that allows you to output a formatted message containing a pair of values. By defining the template parameters, you can specify the types of the two values you want to print.

Tehtävä

Swipe to start coding

Create and call a template with multiple type parameters.

  1. Fill in the ___ to complete the template definition.
  2. Call the template twice:
    • First call: Use <int, std::string> as the template types.
    • Second call: Use <char, float> as the template types.

Ratkaisu

cpp

solution

#include <iostream>

template<typename Type1, typename Type2>
void print_pair(Type1 first, Type2 second)
{
std::cout << "{ pair: " << first << ", " << second << " }" << std::endl;
}

int main()
{
// Specifying one more type
print_pair<int, std::string>(5, "cats");
print_pair<char, float>('q', 12.5);
}

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 1. Luku 4
#include <iostream>

template<___ ___, ___ ___>
void print_pair(___ first, ___ second)
{
std::cout << "{ pair: " << first << ", " << second << " }" << std::endl;
}

int main()
{
// Specify one more type
print_pair<int, ___>(5, "cats");
print_pair<___, ___>('q', 12.5);
}

Kysy tekoälyä

expand
ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

some-alt