简体   繁体   English

模板默认参数在 C++ 中不起作用

[英]Templates Default Arguments not working in C++

#include <iostream>

template<typename T = char>
T cast(T in){
 return in; 
}

int main(){
 std::cout << cast<>(5) << std::endl;
 return 0;
}

Above will print 5 instead of an empty character, as the function is supposed to return a character by default and not an int.上面将打印5而不是空字符,因为该函数应该默认返回一个字符而不是 int。 What am I ding wrong?我错了什么?

Edit: Forcing it with std::cout << cast<char>(5) << std::endl;编辑:用std::cout << cast<char>(5) << std::endl;强制它shows an empty character.显示一个空字符。

The declaration of 5 is an integer by default. 5的声明默认是一个整数。 This causes 'T' to be overridden with the type int, rather than using your default type.这会导致 'T' 被 int 类型覆盖,而不是使用您的默认类型。 If you really wanted the char of value 5 (which you probably don't), you could specify it as '\\x5' .如果您真的想要值 5 的字符(您可能不需要),您可以将其指定为'\\x5'

For the ascii character 5....对于 ascii 字符 5....

int main(){
 std::cout << cast('5') << std::endl;
 return 0;
}

Default types in templates tend to be useful when it's not easy to determine the template type, eg cast from int当不容易确定模板类型时,模板中的默认类型往往很有用,例如从 int 类型转换

template<typename T = char>
T cast(int v){
 return T(v); 
}

and now this will default to a method that casts an int to a char (rather than a int to int).现在这将默认为一种将 int 转换为 char(而不是将 int 转换为 int)的方法。

 std::cout << cast(53) << std::endl;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM