我正在出于学习目的创建自己的String View类,并且正在尝试使其成为100%constexpr。
为了测试它,我有一个成员函数返回一个哈希值。然后,我在switch语句中构造我的字符串视图,并调用相同的成员函数(如果通过),则该成员函数已达到其目的。
要学习,我正在使用/阅读/比较我的实现与Visual Studio 2017最新更新std::string_view
,但是,我注意到,尽管将swap
其标记为constexpr
,但它在Visual Studio和g ++中均不起作用。
这是不起作用的代码:
constexpr Ali::String::View hello("hello");
constexpr Ali::String::View world("world");
// My implementation fails here!
hello.swap(world);
cout << hello << " " << world << endl;
// Visual Studio implementation fails here!
// std::string_view with char const * is not constexpr because of the length
constexpr std::string_view hello("hello");
constexpr std::string_view world("world");
hello.swap(world);
cout << hello << " " << world << endl;
这是if的Visual Studio实现:
constexpr void swap(basic_string_view& _Other) _NOEXCEPT
{ // swap contents
const basic_string_view _Tmp{_Other}; // note: std::swap is not constexpr
_Other = *this;
*this = _Tmp;
}
这是我的课上的内容,与Visual Studio的相似。
constexpr void swap(View & input) noexcept {
View const data(input);
input = *this;
*this = data;
}
所有构造函数和赋值都标记为constexpr。
Visual Studio和g ++都给我类似的错误。
// Visual Studio
error C2662: 'void Ali::String::View::swap(Ali::String::View &) noexcept': cannot convert 'this' pointer from 'const Ali::String::View' to 'Ali::String::View &'
// g++
error: passing 'const Ali::String::View' as 'this' argument discards qualifiers [-fpermissive]
如果swap在constexpr中不起作用,为什么要使用constexpr?
swap
被标记constexpr
为允许在constexpr
函数中调用,例如:
constexpr int foo()
{
int a = 42;
int b = 51;
swap(a, b); // Here swap should be constexpr, else you have error similar to:
// error: call to non-constexpr function 'void swap(T&, T&) [with T = int]'
return b;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句