不是c++17怎么用any
时间: 2023-09-20 16:03:39 浏览: 37
`std::any` 是 C++17 中引入的一个新特性,用于存储任意类型的值,因此如果你要使用 `std::any`,你需要使用 C++17 或更高版本的编译器。
如果你的编译器不支持 C++17,你可以使用其他的实现方式,例如使用模板来实现类似的功能。比如下面这个示例:
```cpp
#include <iostream>
#include <string>
#include <typeindex>
#include <unordered_map>
#include <stdexcept>
class Any {
public:
Any() : m_tpIndex(std::type_index(typeid(void))) {}
Any(const Any& other) : m_ptr(other.Clone()), m_tpIndex(other.m_tpIndex) {}
Any(Any&& other) : m_ptr(std::move(other.m_ptr)), m_tpIndex(other.m_tpIndex) {}
template<typename T, typename = typename std::enable_if<!std::is_same<typename std::decay<T>::type, Any>::value, T>::type>
Any(T&& value) : m_ptr(new Derived<typename std::decay<T>::type>(std::forward<T>(value))), m_tpIndex(typeid(typename std::decay<T>::type)) {}
bool IsNull() const { return !bool(m_ptr); }
template<class T> bool Is() const {
return m_tpIndex == std::type_index(typeid(T));
}
template<class T>
typename std::decay<T>::type& AnyCast() {
if (!Is<T>()) {
throw std::runtime_error("can not cast " + std::string(m_tpIndex.name()) + " to " + std::string(typeid(T).name()));
}
auto derived = dynamic_cast<Derived<typename std::decay<T>::type>*>(m_ptr.get());
return derived->m_value;
}
Any& operator = (const Any& other) {
if (m_ptr == other.m_ptr) {
return *this;
}
m_ptr = other.Clone();
m_tpIndex = other.m_tpIndex;
return *this;
}
private:
struct Base {
virtual ~Base() {}
virtual std::unique_ptr<Base> Clone() const = 0;
};
template<typename T>
struct Derived : Base {
template<typename U>
Derived(U&& value) : m_value(std::forward<U>(value)) { }
std::unique_ptr<Base> Clone() const {
return std::unique_ptr<Base>(new Derived<T>(m_value));
}
T m_value;
};
private:
std::unique_ptr<Base> Clone() const {
if (m_ptr != nullptr) {
return m_ptr->Clone();
}
return nullptr;
}
std::unique_ptr<Base> m_ptr;
std::type_index m_tpIndex;
};
int main() {
Any a = 1;
std::cout << a.AnyCast<int>() << std::endl;
a = std::string("hello");
std::cout << a.AnyCast<std::string>() << std::endl;
try {
a.AnyCast<int>();
} catch (const std::exception& e) {
std::cout << e.what() << std::endl;
}
return 0;
}
```
这段代码定义了一个 `Any` 类,使用模板参数来存储任意类型的值,并在运行时动态判断类型。你可以像使用 `std::any` 一样使用 `Any` 类型的变量,例如调用 `AnyCast` 方法来获取存储的值。