功能模板

模板化也可以應用於具有相同效果的函式(以及更傳統的結構)。

// 'T' stands for the unknown type
// Both of our arguments will be of the same type.
template<typename T>
void printSum(T add1, T add2)
{
    std::cout << (add1 + add2) << std::endl;
}

然後可以以與結構模板相同的方式使用它。

printSum<int>(4, 5);
printSum<float>(4.5f, 8.9f);

在這兩種情況下,template 引數用於替換引數的型別; 結果就像普通的 C++函式一樣(如果引數與模板型別不匹配,則編譯器應用標準轉換)。

模板函式的另一個屬性(與模板類不同)是編譯器可以根據傳遞給函式的引數推斷模板引數。

printSum(4, 5);     // Both parameters are int.
                    // This allows the compiler deduce that the type
                    // T is also int.

printSum(5.0, 4);   // In this case the parameters are two different types.
                    // The compiler is unable to deduce the type of T
                    // because there are contradictions. As a result
                    // this is a compile time error.

此功能允許我們在組合模板結構和函式時簡化程式碼。標準庫中有一個共同的模式,允許我們使用輔助函式 make_X() 來製作 template structure X

// The make_X pattern looks like this.
// 1) A template structure with 1 or more template types.
template<typename T1, typename T2>
struct MyPair
{
    T1      first;
    T2      second;
};
// 2) A make function that has a parameter type for
//    each template parameter in the template structure.
template<typename T1, typename T2>
MyPair<T1, T2> make_MyPair(T1 t1, T2 t2)
{
    return MyPair<T1, T2>{t1, t2};
}

這有什麼用?

auto val1 = MyPair<int, float>{5, 8.7};     // Create object explicitly defining the types
auto val2 = make_MyPair(5, 8.7);            // Create object using the types of the paramters.
                                            // In this code both val1 and val2 are the same
                                            // type.

注意:這不是為了縮短程式碼。這旨在使程式碼更健壯。它允許通過在單個位置而不是在多個位置更改程式碼來更改型別。