Home > Backend Development > C++ > body text

Can You Pass String Literals as Non-Type Template Arguments?

DDD
Release: 2024-11-17 09:04:03
Original
153 people have browsed it

Can You Pass String Literals as Non-Type Template Arguments?

Passing String Literals as Non-Type Template Arguments

Problem Statement:

Can you define a class template with a non-type template parameter that accepts a string literal, such as my_class<"string">?

Solution:

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

Example Code:

#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

Explanation:

In this code, the template parameter str is a const char*, which can point to a string literal or a string variable. The variable teststr is declared as a static const char[] with the string literal "Hello world!". By passing teststr as the template argument, you can effectively access the string literal within the class template.

The above is the detailed content of Can You Pass String Literals 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template