CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 23

Threaded View

  1. #7
    Join Date
    Oct 2008
    Posts
    1,456

    Re: allow literal string only

    as other said it seems impossible with the use of the sole type system ( unless compiler intrisics exist enabling static storage detection ... );

    maybe you can use the preprocessor somehow, something like

    Code:
    #define LITERAL(s) Foo::please_dont_use_me(""s"")
    #define LITERAL_TYPE please_dont_use_me
    
    class Foo
    {
    public:
    	struct please_dont_use_me
    	{
    		explicit please_dont_use_me( const char* str ): value(str) {}
    
    		const char* value;
    	};
    
    	Foo( LITERAL_TYPE str ): str_( str.value ) {}
    
    private:
    	const char* str_;
    };
    
    Foo x( LITERAL("ok") );
    in this way, if you construct a Foo with something that has not the form LITERAL("...") an error should occur ( more specifically, it seems improbable someone accidentally instances a Foo with a Foo :: please_dont_use_me object ... ).

    EDIT: thinking about it, the following might be more expressive ( but roughly equivalent ):

    Code:
    #define LITERAL(s) Foo::please_dont_use_me(""s"")
    
    class Foo
    {
    	struct literal
    	{
    		explicit literal( const char* str ): value(str) {}
    
    		const char* value;
    	};
    
    public:
    	typedef literal please_dont_use_me;
    
    	Foo( literal str ): str_( str.value ) {}
    
    private:
    	const char* str_;
    };
    
    Foo x( LITERAL("ok") );
    BTW, note that it wouldn't protect you against expressions like "Foo x( LITERAL("ok"+"oops") );" and similar ...
    Last edited by superbonzo; July 13th, 2010 at 11:34 AM. Reason: added variation

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