Compile time string processing (changing case, sorting etc.) with constexpr
Hello All,
Back in 2009(*) I had wondered if constexpr would ever allow us to
process strings at compile time (similar to D's CTFE(**)).
So while experimenting with constexpr recently, using gcc4.6, I
noticed that you can come quite close.
That is, in C++11, one should be able to write and compile the
following code (note: all expressions are within the context of a
static_assert and an integer template argument):
template<int N> struct eval { enum { val = n }; };
#define SDUMP(...) cout << #__VA_ARGS__ << " => " << (__VA_ARGS__) <<
endl; \
static_assert( !!eval<__VA_ARGS__>::val, "");
static_assert(__VA_ARGS__, #__VA_ARGS__) \
/**/
int main()
{
using std::cout; using std::endl;
using namespace hel;
SDUMP( tail("abc") == "bc");
SDUMP( append("abc", "efgh") == "abcefgh" );
SDUMP( prepend("abc", "efgh") == "efghabc" );
SDUMP( extract<1,3>("help") == "el" );
SDUMP( insert<1>("jim", "abc") == "jabcim" );
SDUMP( remove("zabzbcdzaz", 'z') == "abbcdazzzz" );
SDUMP( erase("z12z34z5z", 'z') == "12345" );
SDUMP( map("abc", ToUpper()) == "ABC" );
SDUMP( find("0123456777a", '7') == 7 );
SDUMP( isort("03217645") == "01234567");
}
Like me, if anyone else is interested in this capability (and I am not
saying that one should be ;), and has not yet had a chance to
implement it, I have uploaded my implementation into sourcefourge(+)
for their perusal, use and feedback. It has been tested with the may
release of g++ 4.6.
I should provide a disclaimer by stating that as of today, the code is
by no means pristine or exemplary, and asides from many other
stylistic shortcomings, it also resorts to some preprocessor
metaprogramming (ugh!) to generate some of the primitives needed to
provide a convenient interface.
So reader beware ;)
regards,
Faisal Vali
(+) http://constexprstr.svn.sourceforge.net/viewvc/constexprstr/main.cpp?revision=9&view=markup
(*) http://groups.google.com/group/comp.std.c++/browse_thread/thread/9dbb1b527420a3aa
(**) http://www.digitalmars.com/d/2.0/function.html
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]