I’m trying to add a private variable to a class that is constant at compile time and static (does not reside in an individual instance of the class.)
Unfortunately, I cannot get my code to compile. Below is roughly what I’m typing in.
class XFile
{
...
private:
constexpr static string notSupportedMessage("Operating system not supported.");
};
I’m getting error code E0079 Expected a Type Specifier.
I was hoping for some insight in how to properly format the code.
-Brett
You declare static variables inside the class definition, but define static variables outside of the class definition.
// XFile.h
class XFile {
private:
static string notSupportedMessage;
};
// XFile.cpp
string XFile::notSupportedMessage("Operating system not supported.");
Though, considering your message, I wonder if a compile time error might be more appropriate?
Edit: Got sidetracked while composing this response. Seems you beat me to #error.
Using static_assert (http://en.cppreference.com/w/cpp/language/static_assert) could work. You can also use #error (http://en.cppreference.com/w/cpp/preprocessor/error).
Example:
#ifdef _WIN32
// Windows specific code
#elif __linux__
// Linux specific code
#else
#error OS not supported
#endif
As per the linked documentation, it doesn't matter if the string after #error is quoted or not.
To use static_assert, instead of #error, it might look something like this:
static_assert(false, "OS not supported");
Note: You can't simple use preprocessor #defines such as _WIN32, or __linux__ directly with static_assert, since if they're not defined (normally checked by #ifdef/#ifndef), there is no symbol substitution, so the compiler will see an unknown symbol. Also, to get this to compile under Linux, the newer version of C++ must be explicitly enabled: g++ -std=c++11 cppError.cpp
Just tested on Visual Studio 2017. MSVC compiles and runs both with or without quotes. However, if you put quotes around the message, the error message will include the quotes. Ideally, the quotes wouldn't be there, but it compiles and gets the message across clearly.
If someone wants to test on GCC we could compare.
#if defined (linux)
. . .
#else
#error "Operating system not supported."
#endif
Results
Error (active) E0035 #error directive: "Operating system not supported." OP2Utility
Error C1189 #error: "Operating system not supported." OP2Utility
Tested with GCC:
Result:
cppError.cpp:5:2: error: #error OS not supported
#error OS not supported
^