Home  >  Article  >  Backend Development  >  Can C-Style Strings Be Template Arguments in C ?

Can C-Style Strings Be Template Arguments in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-10-30 03:07:29742browse

  Can C-Style Strings Be Template Arguments in C  ?

C-Style Strings as Template Arguments

In the realm of C programming, you may have encountered a dilemma: attempting to employ C-style strings as template arguments. This article delves into the issue and a potential workaround.

The following code snippet illustrates the attempt:

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

int main() {
    X<"String"> x;
    cout << x.GetString();
}

However, despite the lack of compilation errors in the class definition, the instantiation yields an error message. The issue lies in the attempt to use a string literal as a template argument, which is not supported by the compiler.

A simple solution involves replacing the string literal with a character pointer:

<code class="cpp">char global_string[] = "String";

template <char const *str>
struct X {
    const char *GetString() const {
        return str;
    }
};

int main() {
    X<global_string> x;
    cout << x.GetString();
}</code>

This code will successfully compile and execute, allowing you to retrieve the stored string using the GetString method.

Note that with the advent of C 11, it is now possible to employ string literals as template arguments using character packs. However, for compilers supporting earlier C versions, the workaround presented here remains a viable option.

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

Statement:
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