I have made a constexpr
string type, which I call StaticString
. I got this idea from this website.
I am having some weird issues with the compiler treating a variable as a constexpr
on one line, and then not a constexpr
on the next line.
Here is the code:
constexpr StaticString hello = "hello";
constexpr StaticString hello2 = hello + " ";
constexpr StaticString world = "world";
constexpr StaticString both = hello + " world";
constexpr StaticString both2 = hello2 + world;
//This works fine (world is constexpr?)
//constexpr StaticString both3 = "hello " + world;
//ERROR: "world" is not constexpr
int main(void)
{
static_assert(hello[4] == 'o' ,"ERROR");
static_assert(hello == "hello", "ERROR");
static_assert(both2 == "hello world", "ERROR");
}
And here is the definition of StaticString
:
class StaticString{
const char* const str;
const size_t len;
const StaticString* head;
public:
template<size_t N>
constexpr StaticString(const char(&aStr)[N])
: str(aStr), len(N-1), head(nullptr) //Chop off the null terminating char
{
static_assert(N>=1,"String cannot have a negative length");
}
template<size_t N>
constexpr StaticString(const char(&aStr)[N] ,const StaticString* ss) : head(ss), str(aStr),len(N-1) { }
constexpr StaticString(const char* const aStr ,const size_t len,const StaticString* ss = nullptr)
: str(aStr), len(len), head(ss)
{
}
constexpr char GetFromHead(size_t index) const{
return index < head->GetSize() ? (*head)[index] : str[index - head->GetSize()];
}
constexpr char operator[](size_t index) const{
return head ? GetFromHead(index) : str[index];
}
constexpr size_t GetSize() const{
return head ? len + head->GetSize() : len;
}
constexpr bool Equals(const char* const other,size_t len,size_t index = 0) const{
return (other[0] == (*this)[index]) ? (len > 1 ? Equals(&other[1],len-1,index+1) : true) : false;
}
template<size_t N>
constexpr bool operator==(const char(&other)[N]) const{
return Equals(other,N-1);
}
template<size_t N>
constexpr StaticString operator+(const char(&other)[N]) const{
return StaticString(other,this);
}
constexpr StaticString operator+(StaticString other) const{
return StaticString(other.str,other.len,this);
}
};
template<size_t N>
constexpr StaticString operator+(const char(&str)[N],const StaticString& other){
return StaticString(str) + other;
}
So my question is this: why does world
get treated as a constexpr
on one line but not the next?
NOTE: This is the error I get:
'StaticString{((const char*)"world"), 5ull, ((const prototypeInd::util::StaticString*)(&<anonymous>))}' is not a constant expression
Also I am using gcc