【发布时间】:2016-09-27 00:36:48
【问题描述】:
我创建了一个constexpr 字符串类型,我称之为StaticString。我从this 网站得到这个想法。
编译器在将变量视为 constexpr 在一行上,然后在下一行不是 constexpr 时遇到了一些奇怪的问题。
代码如下:
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");
}
这里是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;
}
所以我的问题是:为什么world 在一行上被视为constexpr 而不是下一行?
注意: 这是我得到的错误:
'StaticString{((const char*)"world"), 5ull, ((const prototypeInd::util::StaticString*)(&<anonymous>))}' is not a constant expression
我也在使用gcc
【问题讨论】:
-
另外,
hello2 + world + world也会失败。 -
您使用的是什么编译器? VS2015 不会在
both3的声明/定义上产生错误,但是当它在static_assert()中使用时确实会使编译器崩溃...(C1001:编译器中发生了内部错误。)所以我猜这真的没什么帮助。 -
你解决了吗?用您所做的更正更新问题怎么样?
标签: c++ constexpr compile-time-constant