Home > Backend Development > C++ > body text

Can String Literals be Passed as Non-Type Template Arguments?

Barbara Streisand
Release: 2024-11-20 01:27:03
Original
846 people have browsed it

Can String Literals be Passed as Non-Type Template Arguments?

Passing String Literals to Non-Type Class Template Parameters

Question:

Can a string literal be passed as a non-type argument to a class template, such as in a declaration like my_class<"string">?

Answer:

While directly passing string literals as non-type template arguments is not possible, there is a solution that closely approximates it.

You can utilize a non-type template parameter of type const char* and pass it a const char[] variable with static linkage. This approach shares similarities with passing string literals directly.

Here's a compilable example:

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

The above code declares a class template cts with a non-type template parameter str that takes a constant character pointer. The variable teststr, defined with static linkage, holds the string literal and is passed to the template instantiation.

This method is a viable alternative to directly passing string literals as non-type template arguments.

The above is the detailed content of Can String Literals be Passed as Non-Type Template Arguments?. 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