Home > Backend Development > C++ > Can C-Style Strings Be Used as Template Arguments in C ?

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

Susan Sarandon
Release: 2024-10-30 17:54:31
Original
580 people have browsed it

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

Can C-Style Strings Be Template Arguments?

Your attempt to instantiate a template using a C-style string fails with an error due to the invalid use of a string literal as a template argument.

While C-style strings cannot directly serve as template arguments, there are alternative approaches:

Use a Pointer to a Constant String

One workaround is to use a pointer to a constant string as the template argument:

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

char global_string[] = "String";

int main() {
    X<global_string> x;
    cout << x.GetString();
}
Copy after login

Update: String Literals as Template Arguments with C 11

With C 11 and later, it is possible to use string literals as template arguments by utilizing character packs:

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

int main() {
    X<"S", "t", "r", "i", "n", "g"> x;
    cout << x.GetString();
}</code>
Copy after login

The above is the detailed content of Can C-Style Strings Be Used as Template Arguments in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template