Home  >  Article  >  Backend Development  >  Can String Literals Be Used as Non-Type Template Parameters in C ?

Can String Literals Be Used as Non-Type Template Parameters in C ?

Linda Hamilton
Linda HamiltonOriginal
2024-11-17 06:03:03211browse

Can String Literals Be Used as Non-Type Template Parameters in C  ?

Class Templates with Non-Type String Literals

In C , you may encounter the need to declare class templates with non-type parameters, such as string literals. This query explores the feasibility of this approach and provides a solution.

Non-Type Template Parameter Rationale

You might wish to utilize string literals directly as non-type template parameters for convenience or readability purposes. However, this is not directly supported in C .

A Feasible Workaround

While passing a string literal directly is not possible, a workaround involves using a const char* non-type template parameter and passing it a const char[] variable with static linkage. This method is nearly equivalent to passing a string literal.

Example Implementation

The following code demonstrates this workaround:

#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

  • The class template cts is defined with a const char* non-type template parameter str.
  • A statically linked const char[] variable named teststr is declared and initialized with the string literal "Hello world!".
  • In the main function, an instance of cts is created using teststr as the template argument.
  • The p() member function of the cts object prints the string stored in str.

Conclusion

This workaround allows you to effectively use string literals in class templates as non-type parameters. It provides an alternative solution when direct string literal input is not feasible.

The above is the detailed content of Can String Literals Be Used as Non-Type Template Parameters 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