CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jun 2008
    Location
    Kuala Lumpur, Malaysia
    Posts
    68

    Question Can I pass string literal for template parameter?

    Hi

    I'm gonna implement a dynamic type-cast mechanism. I need to give unique ID to all classes, and I think hash value calculated from the name of class would be appropriate.

    What I'd like to do is something like this:
    Code:
    template <char const* const psz>
    struct _hash_
    {
    	enum {
    		value = *psz
    			? (_hash_<psz+1>::value << 2) | *psz
    			: 0
    	};
    };
    
    
    .........
    
    enum {
    	_classid = _hash_<"cMyClass">::value
    };
    It produces compile errors. I can imagine the reason, (I'm afraid this is fairly stupid idea :S) but I'd like to know if there's any way around.

    Thanks in advance

  2. #2
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Can I pass string literal for template parameter?

    Quote Originally Posted by muse1987
    Hi

    I'm gonna implement a dynamic type-cast mechanism. I need to give unique ID to all classes, and I think hash value calculated from the name of class would be appropriate.
    You have typeid() to get you a compiler-defined name for your classes.

    Regards,

    Paul McKenzie

  3. #3
    Join Date
    Feb 2005
    Location
    "The Capital"
    Posts
    5,306

    Re: Can I pass string literal for template parameter?

    Why don't you make the struct _hash_ as a function that takes a const char*? And no, you cannot templatize on string literals.

  4. #4
    Join Date
    Apr 2007
    Location
    Mars NASA Station
    Posts
    1,436

    Re: Can I pass string literal for template parameter?

    Code:
    template <char const* const psz>
    struct _hash_
    {
    	enum {
    		value = *psz
    			? (_hash_<psz+1>::value << 2) | *psz
    			: 0
    	};
    };

    Should be :

    Code:
    template <const char const*  psz>

    I hope this help.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured