我想在MacOS10.14.4中使用c ++ 1z,例如g++ -std=c++1z test.cpp -o test
。但是clang无法编译代码。
错误如下。
In file included from test.cpp:3:
/Library/Developer/CommandLineTools/usr/include/c++/v1/any:599:5: error: static_assert failed due to requirement 'is_constructible<basic_string<char> &&, _RawValueType
&>::value' "ValueType is required to be an lvalue reference or a CopyConstructible type"
static_assert(is_constructible<_ValueType, _RawValueType &>::value,
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
test.cpp:29:19: note: in instantiation of function template specialization 'std::__1::any_cast<std::__1::basic_string<char> &&>' requested here
auto b = std::any_cast<std::string&&>(a); //< rvalue reference (no need for std::move)
^
1 error generated.
但是相同的代码可以在Linux上工作。代码如下。
#include <string>
#include <iostream>
#include <any>
int main()
{
// simple example
auto a = std::any(12);
std::cout << std::any_cast<int>(a) << '\n';
try {
std::cout << std::any_cast<std::string>(a) << '\n';
}
catch(const std::bad_any_cast& e) {
std::cout << e.what() << '\n';
}
// advanced example
a = std::string("hello");
auto& ra = std::any_cast<std::string&>(a); //< reference
ra[1] = 'o';
std::cout << "a: " << std::any_cast<const std::string&>(a) << '\n'; //< const reference
auto b = std::any_cast<std::string&&>(a); //< rvalue reference (no need for std::move)
// Note, 'b' is a move-constructed std::string, 'a' is now empty
std::cout << "a: " << *std::any_cast<std::string>(&a) //< pointer
<< "b: " << b << '\n';
}
clang版本:Apple LLVM版本10.0.1(clang-1001.0.46.4)
然后我用gcc编译了这段代码,但是也没有用。
答案 0 :(得分:2)
这似乎来自https://developercommunity.visualstudio.com/content/problem/200281/stdany-cast-static-assert-error-because-of-is-cons.html,它来自Microsoft。那里的答案是,这是一个缺陷LWG 2768,因此该修复程序可能尚未在标准库的较早实现中实现。 For example,它将在clang 6.0.0和gcc 7.4中进行编译,但不会在clang 7.0.0和gcc 8.1中进行编译。
原因是您不能接受任何左值的右值引用。通过获取左值引用并对其进行移动或对已移动的any进行右值引用来解决此问题:
std::move(std::any_cast<std::string&>(a));
std::any_cast<std::string&&>(std::move(a));