std::decay
存在的原因是什么?在什么情况下std::decay
是有用的?
发布于 2014-09-09 04:27:40
在处理采用模板类型的参数的模板函数时,您通常具有通用参数。通用参数几乎总是某种类型的引用。它们也是const-volatile限定的。因此,大多数类型特征并不像您预期的那样对它们起作用:
template<class T>
void func(T&& param) {
if (std::is_same<T,int>::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
这里的解决方案是使用std::decay
template<class T>
void func(T&& param) {
if (std::is_same<typename std::decay<T>::type,int>::value)
std::cout << "param is an int\n";
else
std::cout << "param is not an int\n";
}
https://stackoverflow.com/questions/25732386
复制相似问题