-3

The code below explains the problem

constexpr int x = *(reinterpret_cast<const int*>("abcd")); //wrong
constexpr int y = ("abcd")[0]*1l + ("abcd")[1]*256l + ("abcd")[2]*256*256l + ("abcd")[3]*256*256*256l; //ok

How can I do such type casting in constexpr expression?

UPDATE

The reason of doing this:

I'm writing set of templates for manipulating c-style strings in compile time. It uses such representation of string:

template<char... args> struct String {static const char data[sizeof...(args)+1];};
template<char... args> constexpr const char String<args...>::data[sizeof...(args)+1] = {args...,0};

So in my program I can do this:

String<'H','e','l','l','o',' ','w','o','r','l','d','!'>

But I can not do this:

String<"Hello world!">

I have a partial solution for short srtings:

template<int N,char... chrs> struct Int2String : Int2String<(N>>8),N,chrs...> {};
template<char... chrs> struct Int2String<0,chrs...> : String<chrs...> {};
...
Int2String<'Hell'>

It uses c multi-character literals, so works only with strings of length 4 or less, depends on platform, but looks much better. I'm ok with this restrictions, but sometimes I want to use string, defined in library, so I can't change " quotes to ' qoutes. In the example above i'm trying to convert "abcd" to 'abcd'. I expect this to have same representation in memory, so pointer casting looks like a good idea. But I can't do this in compile time.

Denis Sheremet
  • 2,453
  • 2
  • 18
  • 34
  • 2
    You can probably do what you're after with user-defined literals - but you'll need to explain the problem you're trying to solve a bit more. – Mat Dec 31 '15 at 08:38
  • As Mat says, you need to tell us what problem you are trying to solve, what we see is [an XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Oh, and by attempting to cast that pointer to a string literal you break [strict aliasing](http://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule). – Some programmer dude Dec 31 '15 at 08:42
  • A multi-character literal is an int and its value is implementation-defined. – molbdnilo Dec 31 '15 at 12:50

1 Answers1

2

Because things like:

("abcd")[0]

simply equate to:

'a'

which gets integral promotion in the expression:

'a' * 1l

But things like:

(reinterpret_cast<const int*>("abcd")

are trying to get a pointer to static memory which is only known at link time.

Paul Evans
  • 27,315
  • 3
  • 37
  • 54