Skip to content

Instantly share code, notes, and snippets.

@swkwon
Last active November 27, 2017 05:15
Show Gist options
  • Save swkwon/1e59410bdedcba1a48850400b0b6af07 to your computer and use it in GitHub Desktop.
Save swkwon/1e59410bdedcba1a48850400b0b6af07 to your computer and use it in GitHub Desktop.
type deduction in template example
// ----------------------------------
// example 1
template<typename T>
void f(const T& param);
int x = 0;
const int cx = x;
const int& rx = x;
f(x); // param is const int&
f(cx); // param is const int&
f(rx); // param is const int&
// ----------------------------------
// example 2
template<typename T>
void f(T& param);
int x = 0;
const int cx = x;
const int& rx = x;
f(x); // param is int&
f(cx); // param is const int&
f(rx); // param is const int&
// ----------------------------------
// example 3
template<typename T>
void f(T* param);
int x = 27;
const int* px = &x;
f(&x); // param is int*
f(px); // param is const int*
// ----------------------------------
// example 4
template<typename T>
void f(T&& param);
int x = 27;
const int cx = x;
const int& rx = x;
f(x); // param is int&
f(cx); // param is const int&
f(rx); // param is const int&
f(27); // param is int&&
// ----------------------------------
// example 5
template<typename T>
void f(T param);
int x = 0;
const int cx = x;
const int& rx = x;
const char* const ptr = "hello world";
const char[] name = "Takkar";
f(x); // param is int
f(cx); // param is int
f(rx); // param is int
f(ptr); // param is const char* const
f(name); // param is const char*
// ----------------------------------
// example 6
template<typename T>
void f(T& param);
const char[] name = "Takkar";
f(name); // param is const char(&)[7]
// ----------------------------------
// example 7
template<typename T, std::size_t N>
constexpr std::size_t arraySize(T (&)[N]) noexcept
{
return N;
}
const char[] name = "Takkar";
auto size = arraySize(name); // size = 7.
// ----------------------------------
// example 8
void some(int, double);
template<typename T>
f1(T param);
template<typename T>
f2(T& param);
f1(some); // param is void (*)(int, double)
f2(some); // param is void (&)(int, double)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment