在下面的示例中main
可以static_assert
如果字符串文字以'v'
開頭,但verify
不能。如何靜態斷言constexpr函數內的字符串文字的條件?
爲什麼會發生?有沒有一種方法允許verify
到static_assert
條件字符串中的字符?
#include <cstddef>
template <std::size_t N>
constexpr char get_first(const char (&str)[N])
{
static_assert(N>1, "must be > 1");
return str[0];
}
template <std::size_t N>
constexpr void verify(const char (&str)[N])
{
static_assert(str[0] == 'v', "must start from v");
}
int main()
{
static_assert(get_first("value") == 'v', "first must be 'v'"); // succeeds
verify("value"); // fails to compile
}
編譯錯誤:
main.cpp: In instantiation of 'constexpr void verify(const char (&)[N]) [with long unsigned int N = 6]':
main.cpp:19:15: required from here
main.cpp:13:9: error: non-constant condition for static assertion
static_assert(str[0] == 'v', "must start from v");
^~~~~~~~~~~~~
main.cpp:13:9: error: 'str' is not a constant expression
如果你想有一個字符串參數,你可以編譯時斷言,我建議花。 – chris