c++ - 为函数提供字符串或整数

标签 c++ string int

<分区>

我有一个函数(见下文)输出原始输入变量。问题是我不能......

int print(std::string value){
    std::cout << value << std::endl;
return 0;   
}

如果我尝试给出一个 int,它会抛出一个错误。我需要一种方法能够为它提供任何变量类型(稍后检查它是什么类型)并相应地采取行动

最佳答案

我完全重写了这个,因为我误读了问题......

您可以使用模板来创建通用函数:

template <class T>
int print(const T& value)
{
    std::cout << value << std::endl;
    return 0;
}

或者你可以简单地拥有两个不同的函数:

int print(const std::string& value)
{
    std::cout << value << std::endl;
    return 0;
}

int print(int value)
{
    std::cout << value << std::endl;
    return 0;
}

关于c++ - 为函数提供字符串或整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8405742/

相关文章:

C++ Expat XML 标签支持

python - Python 中的字符串压缩

java - 在 "if"语句内将 String 转换为 int

int - Z3:将整数排序转换为位向量

c++ - 如何在 visual studio 中创建 Windows GUI?

c++ - 从 std::vector<char> 到 wchar_t* 的转换

php - 将 PHP 变量与字符串文字混合

ruby - 挤压被空格打断的词而不影响句子中的其他词

string - Python3 TypeError : list indices must be integers or slices, 不是 str

c++ - 如何使用 OpenCV 在 C++ 中将 vector vector 的结构复制到另一个 vector