Home >Backend Development >C++ >Can You Pass String Literals as Non-Type Template Arguments?

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

DDD
DDDOriginal
2024-11-17 09:04:03228browse

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

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!

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