I\'ve wrote several constexpr functions and use them in static_asserts to control some resource limits. But I\'d like to not only enforce compile-time predicate but also to
My VC++ code that print, during compilation, the value of as many compile time constants as you like (e.g. sizeof structures) and continue compiling without error:
// cpptest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
//#define VALUE_TO_STRING2(x) #x
//#define VALUE_TO_STRING(x) VALUE_TO_STRING2(x)
#define TO_STRING(x) #x
#define FUNC_TEMPLATE_MSG(x,y) "[" x "]""["TO_STRING(y)"]"
template
int printN()
{
#pragma message(FUNC_TEMPLATE_MSG(__FUNCSIG__ ,1))
return 0;
};
struct X {
char a[20];
int b;
};
struct Y {
char a[210];
int b;
};
int _tmain(int argc, _TCHAR* argv[])
{
printN();
printN();
//..as many compile time constants as you like
}
Sample output produced by VC++2010. The target value is the first function template parameter value (0x18 and 0xd8 in the example) which VC++ oddly chose to output as hexadecimal value!!
1>------ Build started: Project: cpptest, Configuration: Release Win32 ------
1> cpptest.cpp
1> [int __cdecl printN<0x18,0x0>(void)][1]
1> [int __cdecl printN<0xd8,0x1>(void)][1]
1> Generating code
1> Finished generating code
1> cpptest.vcxproj -> c:\work\cpptest\Release\cpptest.exe
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
The major technique used here is that a during each function template instantiation, the #pragma message() directive is invoked once. The Microsoft specific macro __FUNCSIG__ can display the signature of the containing function and thus the integer value used in each specific instantiation of the function template. Giving COUNTER as the second template parameter is to make sure 2 integers of the same value are still considered different. The 1 in the #pragma directive is of no use here but can be used as an identifier in case we have more than 1 such directive and the output window is full of messy messages.