您好,我正在尝试一个示例,但我不知道如何遵循。我正在尝试设置一个将所有相同的类/类型保存在一起的地图(或其他一些结构)。为此,我的方法是在我的类 ( ResourceManager_t
) 的构造函数中获取所有参数,并且每次我向地图添加新资源时,检查是否可以添加该资源,因为在 Ctor 上已接受。
但我不知道如何填写std::vector<>
以提供任何类型/类。我试过了,std::any
但这似乎不是一个正确的解决方案。
#include <iostream>
#include <memory>
#include <unordered_map>
#include <vector>
#include <type_traits>
#include <cstdint>
#include <utility>
template <typename...> struct is_one_of;
template <typename F> struct is_one_of<F> { static constexpr bool value = false; };
template <typename F, typename S, typename... T>
struct is_one_of<F, S, T...>
{
static constexpr bool value = std::is_same<F, S>::value
|| is_one_of<F, T...>::value;
};
template <typename...> struct is_unique;
template <> struct is_unique<> { static constexpr bool value = true; };
template<typename F, typename... T>
struct is_unique<F, T...>
{
static constexpr bool value = is_unique<T...>::value
&& !is_one_of<F, T...>::value;
};
template<typename... types_t>
struct ResourceManager_t
{
static constexpr inline bool areAllUnique = is_unique<types_t...>::value;
static_assert(areAllUnique);
// Ctor.
ResourceManager_t()
{
constexpr auto size = 1 + sizeof...(types_t);
m_resources.reserve(size);
}
template <typename type_t>
void addResource([[maybe_unused]] type_t add)
{
static constexpr auto oneOf = is_one_of<type_t, types_t...>::value;
static_assert(oneOf);
const auto name = typeid(type_t).name();
m_resources[name].emplace_back(add);
}
void printMap()
{
std::cout << "---------------\n";
for(auto const& [s, vi] : m_resources)
{
std::cout << "[" << s << ": ";
for(auto const& v : vi)
std::cout << static_cast<s>(v) << " ";
std::cout << "]\n";
}
std::cout << "---------------\n";
}
private:
std::unordered_map<std::string, std::vector</*TODO*/>> m_resources{};
};
int main(int, char *[])
{
ResourceManager_t<int, char, uint32_t, uint8_t> rm{};
rm.addResource(1);
rm.addResource('a');
rm.addResource(uint8_t{3U});
rm.addResource(uint8_t{6U});
// rm.addResource(3.F);
rm.printMap();
return 0;
}
我知道我的问题不是很清楚,但我已经尝试了很多东西。我想要的例子
Map:
[int , {1, 2, 3}]
[char , {'a', 'b', 'c']
[uint8_t, {1U, 2U, 3U}]
// int, char, uint8_t can be changed with an int, or whatever that identifies my value.
如果您想要一个编译/执行示例,我已经完成它std::vector<int>
只是为了检查所有其他参数https://godbolt.org/z/hrb1afjxv