首页 >后端开发 >C++ >C 风格字符串可以用作 C 中的模板参数吗?

C 风格字符串可以用作 C 中的模板参数吗?

Susan Sarandon
Susan Sarandon原创
2024-10-30 17:54:31689浏览

Can C-Style Strings Be Used as Template Arguments in C  ?

C 样式字符串可以作为模板参数吗?

您尝试使用 C 样式字符串实例化模板失败,并出现错误无效使用字符串文字作为模板参数。

虽然 C 样式字符串不能直接用作模板参数,但还有替代方法:

使用指向 a 的指针常量字符串

一种解决方法是使用指向常量字符串的指针作为模板参数:

<code class="c++">template <char const>
struct X {
    const char *GetString() const {
        return str;
    }
};

char global_string[] = "String";

int main() {
    X<global_string> x;
    cout <p><strong>更新:使用 C 11 将字符串文字作为模板参数</strong></p>
<p>使用 C 11 及更高版本,可以通过利用字符包将字符串文字用作模板参数:</p>
<pre class="brush:php;toolbar:false"><code class="c++">template <char ...c>
struct X {
    const char (*GetString)() {
        return [](char*... s) { return s; }(c...);
    }
};

int main() {
    X x;
    cout </char></code>

以上是C 风格字符串可以用作 C 中的模板参数吗?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn