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
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 ... ).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") );
EDIT: thinking about it, the following might be more expressive ( but roughly equivalent ):
BTW, note that it wouldn't protect you against expressions like "Foo x( LITERAL("ok"+"oops") );" and similar ...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") );




Reply With Quote