static_assert has the following syntax, which states that a string literal is required.
static_assert ( bool_constexpr , string literal );
Since an instance of a string CAN'T be observed at compile time, the following code is invalid:
const std::string ERROR_MESSAGE{"I assert that you CAN NOT do this."};
static_assert(/* boolean expression */ ,ERROR_MESSAGE);
I have static asserts all over my code, which say the same error message.
Since a string literal is required, would it be best to replace all the repetitive string literals with a MACRO, or is there a better way?
// Is this method ok?
// Should I hand type them all instead?
// Is there a better way?
#define _ERROR_MESSAGE_ "danger"
static_assert(/* boolean expression 1*/ ,_ERROR_MESSAGE_);
//... code ...
static_assert(/* boolean expression 2*/ ,_ERROR_MESSAGE_);
//... code ...
static_assert(/* boolean expression 3*/ ,_ERROR_MESSAGE_);
In C++ you should not define a constant as a macro. Define it as a constant. That's what constants are for.
Also, names beginning with underscore followed by uppercase letter, such as your _ERROR_MESSAGE_, are reserved to the implementation.
That said, yes, it's good idea to use a macro for static asserts, both to ensure a correct string argument and to support compilers that possibly don't have static_assert, but this macro is not C style constant: it takes the expression as argument, and provides that expression as the string message.
Here is my current <static_assert.h>:
#pragma once
// Copyright (c) 2013 Alf P. Steinbach
// The "..." arguments permit template instantiations with "<" and ">".
#define CPPX_STATIC_ASSERT__IMPL( message_literal, ... ) \
static_assert( __VA_ARGS__, "CPPX_STATIC_ASSERT: " message_literal )
#define CPPX_STATIC_ASSERT( ... ) \
CPPX_STATIC_ASSERT__IMPL( #__VA_ARGS__, __VA_ARGS__ )
// For arguments like std::integral_constant
#define CPPX_STATIC_ASSERT_YES( ... ) \
CPPX_STATIC_ASSERT__IMPL( #__VA_ARGS__, __VA_ARGS__::value )
As you can see there are some subtleties involved even when the compiler does have static_assert.
Related
I'd like to accomplish something like the following:
#define FOO(bar, ...) \
static_assert(bar == "foo" || bar == "bazz", "Invalid value for bar") \
...
In other words, I'd like to check at compile time that the value given to the macro is one of the allowed ones. What is the cleanest way for doing a compile time string comparison when comparing against strings of variable length?
You could use string views.
#include <string_view>
using namespace std::string_view_literals;
// Note the sv after the string
#define FOO(bar, ...) \
static_assert(bar == "foo"sv || bar == "bazz"sv, "Invalid value for bar") \
...
The expression "foo"sv invokes a literal operator. It constructs a std::string_view from "foo". std::string_view has overloaded == operators for comparing with strings. These overloaded operators are constexpr which means that they can be evaluated at compile time.
So, it's been a while since I have written anything in C++ and now I'm working on a project using C++11 and macros.
I know that by using the stringify operator I can do this:
#define TEXT(a) #a //expands to "a"
How am I supposed to use the preprocessor for recognizing the tokens like + and * to do this:
#define TEXT(a)+ ??? //want to expand to "a+"
#define TEXT(a)* ??? //want to expand to "a*"
when the input has to be in that syntax?
I have tried doing that:
#define + "+"
but of course it doesn't work. How can I make the preprocessor recognize those tokens?
NOTE:
This is actually part of a project for a small language that defines and uses regular expressions, where the resulting string of the macros is to be used in a regex. The syntax is given and we have to use it as it is without making any changes to it.
eg
TEXT(a)+ is to be used to make the regular expression: std::regex("a+")
without changing the fact that TEXT(a) expands to "a"
First,
#define TEXT(a) #a
doesn't “convert to "a"”. a is just a name for a parameter. The macro expands to a string that contains whatever TEXT was called with. So TEXT(42 + rand()) will expand to "42 + rand()". Note that, if you pass a macro as parameter, the macro will not be expanded. TEXT(EXIT_SUCCESS) will expand to "EXIT_SUCCESS", not "0". If you want full expansion, add an additional layer of indirection and pass the argument to TEXT to another macro TEXT_R that does the stringification.
#define TEXT_R(STUFF) # STUFF
#define TEXT(STUFF) TEXT_R(STUFF)
Second, I'm not quite sure what you mean with TEXT(a)+ and TEXT(a)*. Do you want, say, TEXT(foo) to expand to "foo+"? I think the simplest solution in this case would be to use the implicit string literal concatenation.
#define TEXT_PLUS(STUFF) # STUFF "+"
#define TEXT_STAR(STUFF) # STUFF "*"
Or, if you want full expansion.
#define TEXT_R(STUFF) # STUFF
#define TEXT_PLUS(STUFF) TEXT_R(STUFF+)
#define TEXT_STAR(STUFF) TEXT_R(STUFF*)
Your assignment is impossible to solve in C++. You either misunderstood something or there’s an error in the project specification. At any rate, we’ve got a problem here:
TEXT(a)+ is to be used to make the regular expression: std::regex("a+") without changing the fact that TEXT(a) expands to "a" [my emphasis]
TEXT(a) expands to "a" — meaning, we can just replace TEXT(a) everywhere in your example; after all, that’s exactly what the preprocessor does. In other words, you want the compiler to transform this C++ code
"a"+
into
std::regex("a+")
And that’s simply impossible, because the C++ preprocess does not allow expanding the + token.
The best we can do in C++ is use operator overloading to generate the desired code. However, there are two obstacles:
You can only overload operators on custom types, and "a" isn’t a custom type; its type is char const[2] (why 2? Null termination!).
Postfix-+ is not a valid C++ operator and cannot be overloaded.
If your assignment had just been a little different, it would work. In fact, if your assignment had said that TEXT(a)++ should produce the desired result, and that you are allowed to change the definition of TEXT to output something other than "a", then we’d be in business:
#include <string>
#include <regex>
#define TEXT(a) my_regex_token(#a)
struct my_regex_token {
std::string value;
my_regex_token(std::string value) : value{value} {}
// Implicit conversion to `std::regex` — to be handled with care.
operator std::regex() const {
return std::regex{value};
}
// Operators
my_regex_token operator ++(int) const {
return my_regex_token{value + "+"};
}
// more operators …
};
int main() {
std::regex x = TEXT(a)++;
}
You don't want to jab characters onto the end of macros.
Maybe you simply want something like this:
#define TEXT(a, b) #a #b
that way TEXT(a, +) gets expanded to "a" "+" and TEXT(a, *) to "a" "*"
If you need that exact syntax, then use a helper macro, like:
#define TEXT(a) #a
#define ADDTEXT(x, y) TEXT(x ## y)
that way, ADDTEXT(a, +) gets expanded to "a+" and ADDTEXT(a, *) gets expanded to "a*"
You can do it this way too:
#define TEXT(a) "+" // "a" "+" -> "a+"
#define TEXT(a) "*" // "a" "*" -> "a*"
Two string literals in C/C++ will be joined into single literal by specification.
I have a C++ library that uses the predefined macro __FUNCTION__, by way of crtdefs.h. The macro is documented here. Here is my usage:
my.cpp
#include <crtdefs.h>
...
void f()
{
L(__FUNCTIONW__ L" : A diagnostic message");
}
static void L(const wchar_t* format, ...)
{
const size_t BUFFERLENGTH = 1024;
wchar_t buf[BUFFERLENGTH] = { 0 };
va_list args;
va_start(args, format);
int count = _vsnwprintf_s(buf, BUFFERLENGTH, _TRUNCATE, format, args);
va_end(args);
if (count != 0)
{
OutputDebugString(buf);
}
}
crtdefs.h
#define __FUNCTIONW__ _STR2WSTR(__FUNCTION__)
The library (which is compiled as a static library, if that matters) is consumed by another project in the same solution, a WPF app written in C#.
When I compile the lib, I get this error:
identifier "L__FUNCTION__" is undefined.
According to the docs, the macro isn't expanded if /P or /EP are passed to the compiler. I have verified that they are not. Are there other conditions where this macro is unavailable?
You list the error as this:
identifier "L__FUNCTION__" is undefined.
Note it's saying "L__FUNCTION__" is not defined, not "__FUNCTION__".
Don't use __FUNCTIONW__ in your code. MS didn't document that in the page you linked, they documented __FUNCTION__. And you don't need to widen __FUNCTION__.
ETA: I also note that you're not assigning that string to anything or printing it in anyway in f().
Just use
L(__FUNCTION__ L" : A diagnostic message");
When adjacent string literals get combined, the result will be a wide string if any of the components were.
There's nothing immediately wrong with using L as the name of a function... it's rather meaningless however. Good variable and function identifiers should be descriptive in order to help the reader understand the code. But the compiler doesn't care.
Since your L function wraps vsprintf, you may also use:
L(L"%hs : A diagnostic message", __func__);
since __func__ is standardized as a narrow string, the %hs format specifier is appropriate.
The rule is found in 2.14.5p13:
In translation phase 6 (2.2), adjacent string literals are concatenated. If both string literals have the same encoding-prefix, the resulting concatenated string literal has that encoding-prefix. If one string literal has no encoding-prefix, it is treated as a string literal of the same encoding-prefix as the other operand. If a UTF-8 string literal token is adjacent to a wide string literal token, the program is ill-formed. Any other concatenations are conditionally-supported with implementation-defined behavior.
I think the definition of __FUNCTIONW__ is incorrect. (I know you did not write it.)
From: http://gcc.gnu.org/onlinedocs/gcc/Function-Names.html
These identifiers are not preprocessor macros. In GCC 3.3 and earlier,
in C only, __FUNCTION__ and __PRETTY_FUNCTION__ were treated as string
literals; they could be used to initialize char arrays, and they could
be concatenated with other string literals. GCC 3.4 and later treat
them as variables, like __func__. In C++, __FUNCTION__ and
__PRETTY_FUNCTION__ have always been variables.
At least in current GCC then you cannot prepend L to __FUNCTION__, because it is like trying to prepend L to a variable. There probably was a version of VC++ (like there was of GCC) where this would have worked, but you are not using that version.
I'm using a unit test framework that relies on a REQUIRE macro for performing assertions.
Simplified, the macro works like this:
#define REQUIRE( expr ) INTERNAL_REQUIRE( expr, "REQUIRE" )
Which is defined similar to this:
#define INTERNAL_REQUIRE( expr, macroName ) \
PerformAssertion( macroName, #expr, expr );
PerformAssertion's first two parameters are of the type: const char*. The reason for the second parameter (#expr) is so the exact expression that was asserted can be logged. This is where the issue lies. The preprocessor expands the expression before it is passed as a const char *, so it's not the same expression that was originally asserted.
For instance:
REQUIRE( foo != NULL );
Would result in this call:
PerformAssertion( "REQUIRE", "foo != 0", foo != 0 );
As you can see, the expression is partially expanded, e.g. the expression foo != NULL appears in the log as foo != 0. The NULL (which is a macro defined to be 0) was expanded by the C preprocessor before building the assertions message text. Is there a way I can ignore or bypass the expansion for the message text?
EDIT: Here's the solution, for anyone curious:
#define REQUIRE( expr ) INTERNAL_REQUIRE( expr, #expr, "REQUIRE" )
#define INTERNAL_REQUIRE( expr, exprString, macroName ) \
PerformAssertion( macroName, exprString, expr );
Try making the stringifying before the call to the internal require. Your problem is that it is passed to internal require in the second expansion which expands NULL. If you make the stringifying happen before that, e.g. In the require macro, it will not expand the NULL.
Here is what's going on: since you macro where the "stringization" operator # is applied is second-level, the sequence of operations works as follows:
Preprocessor identifies the arguments of REQUIRE(NULL) and performs argument substitution as per C 6.10.3.1. At this point, the replacement looks like INTERNAL_REQUIRE( 0, "REQUIRE" ), because NULL is expanded as 0.
Preprocessor continues expanding the macro chain with INTERNAL_REQUIRE; at this point, the fact that the macro has been called with NULL is lost: as far as the preprocessor is concerned, the expression passed to INTERNAL_REQUIRE is 0.
A key to solving this problem is in this paragraph from the standard:
A parameter in the replacement list, unless preceded by a # or ## preprocessing token or followed by a ## preprocessing token (see below), is replaced by the corresponding argument after all macros contained therein have been expanded.
This means that if you would like to capture the exact expression, you need to do it in the very first level of the macro expansion.
Is this possible to do using templates?
There are two string constants. They come from defines in different modules. They must be equal, or I shall raise compile-time error if they are not equal. Can I do this using templates?
#define MY_STRING "foo"
CompileAssertIfStringsNotEqual(MY_STRING, HIS_STRING);
P.S. I was deluded by assuming that "abc"[0] is constant expression. It is not. Weird omission in the language. It would be possibe had "abc"[0] been constand expression.
This is only possible with C++0x. No chance with C++03.
EDIT: Constexpr function for C++0x. The following works with GCC4.6, however the Standard is not explicit in allowing it, and a small wording tweak was and is being considered to make the spec allow it.
constexpr bool isequal(char const *one, char const *two) {
*one == *two && (!*one || isEqual(one + 1, two + 1));
}
static_assert(isequal("foo", "foo"), "this should never fail");
static_assert(!isequal("foo", "bar"), "this should never fail");
The compiler is required to track the reference to characters of the string literals already, throughout all the recursions. Just the final read from characters isn't explicitly allowed (if you squint, you can read it as being allowed, IMO). If your compiler doesn't want to accept the above simple version, you can make your macro declare arrays and then compare those
#define CONCAT1(A, B) A ## B
#define CONCAT(A, B) CONCAT1(A, B)
#define CHECK_EQUAL(A, B) \
constexpr char CONCAT(x1, __LINE__)[] = A, \
CONCAT(x2, __LINE__)[] = B; \
static_assert(isequal(CONCAT(x1, __LINE__), CONCAT(x2, __LINE__)), \
"'" A "' and '" B "' are not equal!")
That's definitely fine.
CHECK_EQUAL("foo", "foo"); /* will pass */
CHECK_EQUAL("foo", "bar"); /* will fail */
Note that CHECK_EQUAL can be used inside of functions. The FCD did make a change to allow constexpr functions to read from automatic arrays in their invocation substitution. See DR1197.
No. You can not. Not even with boost::mpl or the boost preprocessor library. Even if you were to stipulate that the compiler could coalesce all duplicate string references into the same pointer value at compile-time, the pointer value does not exist until link-time. What you want to implement happens at preprocessor time, and then is asserted at compile-time.