Re: static const & literal
Is there any solution to this without have to write the string twice in the Code?
Re: static const & literal
What about good old #define directive?
Re: static const & literal
First, I wonder how you got this to compile in the first place (aside from the missing semicolon):
Quote:
Originally Posted by
Gener4tor
c++:
struct StyleConstants
{
static const CString TestConst="UniqueStringWhichShouldBeOnlyWrittenOnceInTheCode";
}
When I try this (with std::string in place of the CString though, because I don't have MFC here), I get an error C2864. It only works for me with TestConst at file scope (however, you may put it into a namespace).
Quote:
error C3887: 'StyleConstNet::TestConst: the initializer for a literal data member must be a constant expression
Unfortunately this is the plain truth. The initializer for a literal member must be a compile-time constant. The CString, however, is an object that needs to be constructed at runtime, so it doesn't work that way. (And I'm not even sure you actually can simply assign a CString to a .NET System::String ^ at all, even away from the context of initialization.)
If you really don't want to write the constant twice in your code (which I can understand because it complicates maintainance), I think the adequate solution here is a really trivial one, #define the string literal as s macro:
Code:
#define TESTCONST "UniqueStringWhichShouldBeOnlyWrittenOnceInTheCode"
// c++:
struct StyleConstants
{
static const CString TestConst=TESTCONST;
}
// cli:
public ref class StyleConstNet
{
literal String^ TestConst=TESTCONST;
}
Please use code tags when posting code.
Ah, and... welcome to CodeGuru! :)
EDIT: Alex F was quicker yet again... ;)
Re: static const & literal
Quote:
Originally Posted by
Eri523
Alex F was quicker yet again... ;)
Maybe because my answer was a bit shorter :)
Re: static const & literal
Quote:
Originally Posted by
Alex F
Maybe because my answer was a bit shorter :)
Certainly. You know I always tend to those elaborate (wordy?) replies... :rolleyes: