is it possible in modern c++ to pass string literal as parameter to c++ template?

  • A+

Is it possible in "modern C++" (C++17 or greater) to pass a string literal as a parameter to a C++ template? I realize you could do this with constructor argument, I just thought it would be more convenient to have it as a template argument, rather than buried deep in the cpp file. Was curious if maybe this was a new feature of modern C++. See Pseudo code below of what I'm trying to do:

Pseudo-code Example:

// Header File ///////////////////////// template<string_literal Name> class ModuleBase { public:      ModuleBase(); {      string name; };  class xyz : ModuleBase<"xyz"> { public:     xyz(); };  // Cpp File ////////////////////////// template<string_literal Name> ModuleBase<Name>::ModuleBase() {          name = Name; }  xyz::xyz() : ModuleBase() {  } 


Yes, in .

The problem was that determining uniqueness of a template non-type argument was difficult.

adds in a <=> spaceship operator comparison. If it is constexpr and returns the right type (and a few other requirements; see p0732), the type can be used as a non-type template argument.

Such types can be constructed from raw "strings" in constexpr constructors, including using deduction guides to make them auto-size themselves.

As the size of the data stored is probably going to be part of the type, you'll want to take the type as an auto typed non-type parameter or otherwise auto-deduced type.

Note that placing the implementation of your template in a cpp file is usually a bad idea. But that is another question.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: