gpt4 book ai didi

c++ - 在编译时定义字符串/字 rune 字

转载 作者:太空宇宙 更新时间:2023-11-04 14:53:09 27 4
gpt4 key购买 nike

如何确定函数中传递的参数是字符串还是字符(不确定如何正确调用它)文字?

我的函数(不正确):

void check(const char* str)
{
// some code here
}

我想调用它:

int main()
{
check("Hello"); // Correct call

std::string hello = "Hello";
check(hello.c_str()); // Must be compile error here
}

最佳答案

对于这两种解决方案,我将您的 check 函数重命名为 check_impl 并包装它。

这不能单独用编译器完成,但我们可以接近:

template <std::size_t N>
void check(char const (&str)[N]) {
return check_impl(str);
}

这只接受对 const char 数组的引用,这并不常见。但是您仍然可以传递命名数组而不是字符串文字。

进入预处理器:

#define check(str) check_impl("" str)

这个非常简单的宏只是为您的参数添加一个空文字。如果参数是另一个字符串字面量,编译器会合并它们,否则会出现语法错误。

关于c++ - 在编译时定义字符串/字 rune 字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40633675/

27 4 0
文章推荐: css - Eclipse Web 应用程序元素。引入的 CSS 属性不起作用
文章推荐: css - Bootstrap 边栏上图标旁边的文本对齐
文章推荐: html - "float: left"使
  • 元素忽略它包裹在其中的
  • Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com