std::any::type

来自cppreference.com
< cpp‎ | utility‎ | any
 
 
工具库
通用工具
格式化库 (C++20)
(C++11)
关系运算符 (C++20 中弃用)
整数比较函数
(C++20)(C++20)(C++20)
(C++20)
swap 与类型运算
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
常用词汇类型
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)

初等字符串转换
(C++17)
(C++17)
栈踪
 
 
const std::type_info& type() const noexcept;
(C++17 起)

查询所含类型。

参数

(无)

返回值

若实例非空则为所含值的 typeid ,否则为 typeid(void)

示例

示例演示在编译和运行时注册新观览器的 std::any 观览器手法。

#include <type_traits>
#include <any>
#include <functional>
#include <iomanip>
#include <iostream>
#include <typeindex>
#include <typeinfo>
#include <unordered_map>
#include <vector>
 
template<class T, class F>
inline std::pair<const std::type_index, std::function<void(std::any const&)>>
    to_any_visitor(F const &f)
{
    return {
        std::type_index(typeid(T)),
        [g = f](std::any const &a)
        {
            if constexpr (std::is_void_v<T>)
                g();
            else
                g(std::any_cast<T const&>(a));
        }
    };
}
 
static std::unordered_map<
    std::type_index, std::function<void(std::any const&)>>
    any_visitor {
        to_any_visitor<void>([]{ std::cout << "{}"; }),
        to_any_visitor<int>([](int x){ std::cout << x; }),
        to_any_visitor<unsigned>([](unsigned x){ std::cout << x; }),
        to_any_visitor<float>([](float x){ std::cout << x; }),
        to_any_visitor<double>([](double x){ std::cout << x; }),
        to_any_visitor<char const*>([](char const *s)
            { std::cout << std::quoted(s); }),
        // ……添加更多你的类型的特化……
    };
 
inline void process(const std::any& a)
{
    if (const auto it = any_visitor.find(std::type_index(a.type()));
        it != any_visitor.cend()) {
        it->second(a);
    } else {
        std::cout << "Unregistered type "<< std::quoted(a.type().name());
    }
}
 
template<class T, class F>
    inline void register_any_visitor(F const& f)
{
    std::cout << "Register visitor for type "
              << std::quoted(typeid(T).name()) << '\n';
    any_visitor.insert(to_any_visitor<T>(f));
}
 
auto main() -> int
{
    std::vector<std::any> va { {}, 42, 123u, 3.14159f, 2.71828, "C++17", };
 
    std::cout << "{ ";
    for (const std::any& a : va) {
        process(a);
        std::cout << ", ";
    }
    std::cout << "}\n";
 
    process(std::any(0xFULL)); //< 反注册 "y" 的类型( unsigned long long )
    std::cout << '\n';
 
    register_any_visitor<unsigned long long>([](auto x) {
        std::cout << std::hex << std::showbase << x; 
    });
 
    process(std::any(0xFULL)); //< OK : 0xf
    std::cout << '\n';
}

可能的输出:

{ {}, 42, 123, 3.14159, 2.71828, "C++17", }
Unregistered type "y"
Register visitor for type "y"
0xf

参阅

针对 type_info 对象的包装,它能用作关联容器和无序关联容器的索引。
(类)