// 2. Array-to-pointer conversion
template
// 3. Function-to-pointer conversion
template
// Example function to be passed void sampleFunction() { std::cout « “Function-to-pointer conversion” « std::endl; }
int main() { // 1. Lvalue-to-rvalue conversion int a = 42; printValue(a); // Lvalue ‘a’ is converted to rvalue
// **2. Array-to-pointer conversion**
int arr[] = {10, 20, 30};
printArray(arr); // Array 'arr' decays to pointer
// **3. Function-to-pointer conversion**
callFunction(sampleFunction); // Function name decays into a pointer
return 0; } ```
P is not a reference type.A can be another pointer or pointer to member type that can be converted to the deduced A via a qualification conversion.
#include <iostream>
template <typename Type>
Type min3( Type* const array, const int size) {
Type min_value = array[0];
for (int i = 1; i < size; ++i) {
if (array[i] < min_value) {
min_value = array[i];
}
}
return min_value;
}
int main() {
int numbers[] = {42, 23, 56, 1, 78, 34, 89, 12, 5, 90};
int* ptr1 = numbers;
const int* ptr2 = numbers;
int* const ptr3 = numbers;
const int* const ptr4 = numbers;
std::cout << min3(ptr1, 10) << std::endl;
// error: Type = const int, resulting in min_value is read-only
std::cout << min3(ptr2, 10) << std::endl;
std::cout << min3(ptr3, 10) << std::endl;
// error: Type = const int, resulting in min_value is read-only
std::cout << min3(ptr4, 10) << std::endl;
return 0;
}
T<args>, T<args>&, or T<args>*, where the parameter list args contains at least one of the template parameters.
#include <iostream>
#include <typeinfo>
template <typename T>
struct Base {
T value;
};
template <typename T>
struct Derived : Base<T> { /* ... */ };
template <typename T>
void show(Base<T>& obj) {
std::cout << "Template argument deduction succeeded! T = "
<< typeid(T).name() << ", value = " << obj.value << "\n";
}
int main() {
Derived<int> d;
d.value = 42;
show(d);
return 0;
}
#include <iostream>
template<typename T>
void foo(T, T){ std::cout << "foo was called" << std::endl; }
int main(){
double d = 1.0;
foo(1, d); // error: no matching function for call to ‘foo(int, double&)’
foo(1.0, d); // foo was called
return 0;
}
#include <iostream>
template<typename T>
void foo(T, int){ std::cout << "foo was called" << std::endl; }
int main(){
double d = 1.0;
foo(1, d); // foo was called
return 0;
}
U.
#include <iostream>
template<typename T, typename U>
void foo(T){ }
int main(){
foo(2);
return 0;
}
template
template
template
template
int main() { int i = 42; int& ri = i; const int ci = 100; const int& cri = ci;
func1(i); // 00
func1(ci); // 00
func1(ri); // 00
func1(cri); // 00
func2(i); // 00
func2(ci); // 00
func2(ri); // 00
func2(cri); // 00
func3(i); // 00
func3(ci); // 10
func3(ri); // 00
func3(cri); // 10
func4(i); // 00
func4(ci); // 00
func4(ri); // 00
func4(cri); // 00 } ```