What are the reasons for the existence of std::decay? In what situations is std::decay useful?
When dealing with template functions that take parameters of a template type, you often have universal parameters. Universal parameters are almost always references of one sort or another. They're also const-volatile qualified. As such, most type traits don't work on them as you'd expect:
template
void func(T&& param) {
if (std::is_same::value)
std::cout << "param is an int\n";
else
std::cout << "param is not an int\n";
}
int main() {
int three = 3;
func(three); //prints "param is not an int"!!!!
}
http://coliru.stacked-crooked.com/a/24476e60bd906bed
The solution here is to use std::decay:
template
void func(T&& param) {
if (std::is_same::type,int>::value)
std::cout << "param is an int\n";
else
std::cout << "param is not an int\n";
}
http://coliru.stacked-crooked.com/a/8cbd0119a28a18bd