Home >Backend Development >C++ >How can I use string literals as non-type template arguments in C ?

How can I use string literals as non-type template arguments in C ?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-29 15:14:14962browse

How can I use string literals as non-type template arguments in C  ?

Passing String Literals as Non-Type Template Arguments

In the realm of C templating, declaring a class template that accepts a string literal as a non-type template parameter can be a perplexing task. Many programmers desire the ability to specify a string literal directly in a template declaration, such as my_class<"string">.

To address this need, while C does not directly allow passing string literals as non-type arguments, a solution utilizing const character arrays can be employed. By defining a statically linked const char[] variable and passing it as the template parameter, we achieve a similar effect to using string literals.

Here's a compilable code snippet that demonstrates this approach:

#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();
}

In this example, a statically linked const char[] variable named teststr is defined with the value "Hello world!". By passing teststr as the non-type template parameter to the cts class template, we effectively achieve the desired behavior of using a string literal.

Running this code produces the following output:

Hello world!

This technique provides a workaround to the lack of direct support for passing string literals as non-type template arguments in C , allowing programmers to define class templates that accept string-like values in a convenient manner.

The above is the detailed content of How can I use string literals as non-type 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