Passing a string literal as a parameter to a C++ template class

c string literal
passing string literal to function c++
treat the string as an argument to avoid this
how to pass a string as an argument
passing strings as arguments in c
passing const char* to function in c
c pass string to function by reference
passing string variables in c

I want a class which takes two parameters in its constructor. The first can be either an int, double or float, so <typename T>, and the second is always a string literal "my string", so I guess const char * const.

Can anyone give me some compilable code which declares a simple class template as described and declares an object of that class?

Thanks

Sorry, C++ does not currently support the use of string literals (or real literals) as template parameters.

But re-reading your question, is that what you are asking? You cannot say:

foo <"bar"> x;

but you can say

template <typename T>
struct foo {
   foo( T t ) {}
};

foo <const char *> f( "bar" );

String Literals and char, In both C and C++, the results of attempting to modify a string literal are undefined. parameter declared as char* should no longer be passed as a string literal. I am trying to concatenate "Label: " and *msg and use the result as a parameter in a function. *msg is a pointer to a character array. Other examples of this function use either string

Further from Neil's answer: one way to using strings with templates as you want is to define a traits class and define the string as a trait of the type.

#include <iostream>

template <class T>
struct MyTypeTraits
{
   static const char* name;
};

template <class T>
const char* MyTypeTraits<T>::name = "Hello";

template <>
struct MyTypeTraits<int>
{
   static const char* name;
};

const char* MyTypeTraits<int>::name = "Hello int";

template <class T>
class MyTemplateClass
{
    public:
     void print() {
         std::cout << "My name is: " << MyTypeTraits<T>::name << std::endl;
     }
};

int main()
{
     MyTemplateClass<int>().print();
     MyTemplateClass<char>().print();
}

prints

My name is: Hello int
My name is: Hello

How to pass a string literal as a parameter to a C++ template class , So a literal string is both an immutable char array and an immutable char pointer. Because we generally have literals and std::string together in the same program, std::string can emplace an instance as a parameter if it receives a const char* as its parameter. Passing a string literal as a parameter to a C++ template class The goal was to find a comfortable way to pass a string literal to the useless Get function, which

You can have a const char* non-type template parameter, and pass it a const char[] variable with static linkage, which is not all that far from passing a string literal directly.

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

http://coliru.stacked-crooked.com/a/64cd254136dd0272

STR30-C. Do not attempt to modify string literals, According to the C Standard, 6.4.5, paragraph 3 [ISO/IEC 9899:2011]: a string literal is passed to the (pointer to non- const ) parameter of the POSIX function This compliant solution uses a named array instead of passing a string literal:. Or in other words: Literal strings in C are bytes delimited with '\0' and found via their address. So When you pass "abc" to a function ,you are actually passing the address (a char * pointer) to the function as parameter. Also string literals should be treated read-only in C. – U. Windl Sep 4 '19 at 0:15

This is a solution with MPLLIBS to pass a strings as template arguments ( C++11 ).

#include <iostream>
#include <mpllibs/metaparse/string.hpp> // https://github.com/sabel83/mpllibs
#include <boost/mpl/string.hpp>

// -std=c++11

template<class a_mpl_string>
struct A
{
  static const char* string;
};

template<class a_mpl_string>
const char* A< a_mpl_string >
::string { boost::mpl::c_str< a_mpl_string >::value };  // boost compatible

typedef A< MPLLIBS_STRING ( "any string as template argument" ) > a_string_type;

int main ( int argc, char **argv )
{
  std::cout << a_string_type{}.string << std::endl;
  return 0;
}

prints:

any string as template argument

The lib on github: https://github.com/sabel83/mpllibs

DCL13-C. Declare function parameters that are , In C, function arguments are passed by value rather than by reference. This violates STR05-C. Use pointers to const when referring to string literals and  This warning is raised when a literal string is passed as a value to a parameter or property and one or more of the following cases is true: The LocalizableAttribute attribute of the parameter or property is set to true. The name of the string parameter that is passed to a Console.Write or Console.WriteLine method is either "value" or "format".

inline const wchar_t *GetTheStringYouWant() { return L"The String You Want"; }

template <const wchar_t *GetLiteralFunc(void)>
class MyType
{
     void test()
     {
           std::cout << GetLiteralFunc;
     }    
}

int main()
{
     MyType<GetTheStringYouWant>.test();
}

Try it with pasing the address of a function as the template argument.

Declaring a String Literal as a Pointer, Again, in the code you can use the string variable to reference the text — but that's about it. Altering the string or passing it to a function renders  If it precedes a formal parameter in the macro definition, the actual argument passed by the macro invocation is enclosed in quotation marks and treated as a string literal. The string literal then replaces each occurrence of a combination of the stringizing operator and formal parameter within the macro definition.

Through C to C++: A Complete Programming Course, Caution: potential programthe address of the argument data_string is passed to containing the string constant "Globe" is passed to the parameter which paper​  The example passes a string literal to function templates that declare their parameter to be a reference or nonreference respectively. Both function templates use the typeid operator to print the type of the instantiated parameters.

Passing Strings as Arguments to Functions in C, Hey everyone! If I have a function that takes a pointer to char (i.e. char array) as an argument, can I pass a "string literal" (I think that is the You can initialize and pass a new array in one step, as is shown in the following example. PrintArray(new int[] { 1, 3, 5, 7, 9 }); Example. In the following example, an array of strings is initialized and passed as an argument to a DisplayArray method for strings. The method displays the elements of the array.

C Programming Course Notes - Character Strings, String literals are passed to functions as pointers to a stored string. For example, given the statement: printf( "Please enter a positive value for the angle: " );. the  The string is not being passed directlyto Print, but rather undergoes an implicit conversion to our class literal StringLiteral. Note that this conversion depends on C++17’s added support of template parameter deduction using constructor arguments (the value of Ncan be deduced from constructor argument str). 1 2

Comments
  • If you mean template parameters, see Neil's answer below; but if you mean ctor parameters (as it seems you wrote?) then you don't even need a template. Please clarify.
  • The string literal "my string" is of type const char[10]
  • Do C++0x variadic templates support integral arguments? You could probably do something nasty with representing strings as lists of chars.
  • maybe you might hack around with 4 char long literals (supported by all compilers?) and variadic templates -- it would make a nice answer on SO but it would look ugly in production code :)
  • Neil, that is looking very good, but since I am dumb, can you correct this code? I tried to adapt yours to take two params, which ought to be simple enough ... <pre> template<typename E, typename S> class Event { public: Event(E eventId, S eventName); // constructor private: E _eventId; char _eventName[MAX_EVENT_NAME_LENGTH + 1]; }; </pre> and try to instantiate with <pre> enum enum1 {eventA, eventB}; Event<enum1, const char *> testEventA(eventA, "A"); </pre> but I get compiler errors - see next comment, running out of space
  • sht!! How to format comments, if PRE doesn't work? - trying to instantiate ‘template<class E, class S> class - initializer expression list treated as compound expression - invalid conversion from ‘const char’ to ‘int’ test_fsm.cpp - invalid type in declaration before ‘(’ token test_fsm.cpp - template argument for ‘template<class E, class S> class Event’ uses local type ‘testFsmClasses::TesEventConstructor()::enum1’
  • @Mawg Edit your original question. ANd never try to use HTML to format the question or your answers. Use those little buttons above the editor.
  • This looks interesting. Can it be massages to pass the string as a parameter and show and example of declaring an object?
  • @mawg As per your example under Niel's answer (really you should update your question, saying "Update: This is what I want"), you want to differentiate between classes based (only) on a string template parameter. This is impossible (see Niel's answer). But if you want to differentiate between classes based on EventId, then you can use the EventName as a field in the trait class as per my answer.
  • @mawg Also see my another newly added answer.
  • Thanks, that's just what I needed ;)
  • This is just what I needed. I tuned it a bit with one preprocessor macro which takes three parameters: A type name, a string literal, and the class template parameter(s). The macro then defines the template specialization for the template parameter(s), sets the trait to the string literal, and finally typedefs the class template with the template parameters as the type name. So using this mechanism is reduced to one simple preprocessor macro call instead of a dozen lines of C++ template code.
  • This should be pinned answer. I wish I didn't miss this before I find out it by myself... a month later than I need this.