Home >Backend Development >C++ >How Can I Pass String Literals as Template Arguments in C ?

How Can I Pass String Literals as Template Arguments in C ?

Susan Sarandon
Susan SarandonOriginal
2024-11-29 12:20:10293browse

How Can I Pass String Literals as Template Arguments in C  ?

Passing a String as a Template Argument

In C , when defining a class template, non-type parameters can also be specified. A common use case involves passing string literals as such parameters. Here's how this can be achieved:

While it's not possible to directly pass a string literal as a non-type template argument, you can utilize a const char* parameter and pass a const char[] variable with static linkage.

#include <iostream>

template<const char *str>
struct Cts {
    void p() { std::cout << str; }
};

static const char testStr[] = "Hello world!";
int main() {
    Cts<testStr> o;
    o.p();
}

Here, the Cts template has a non-type parameter str of type const char*. We define a static variable testStr of type const char[] and pass it as the argument to Cts.

This approach effectively mimics the behavior of passing string literals as template arguments and allows you to create class templates that operate on specific string values.

The above is the detailed content of How Can I Pass String Literals as 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