こんにちは、例を試していますが、従う方法がわかりません。同じクラス/タイプをすべて一緒に保存するマップ (またはその他の構造) を設定しようとしています。そのために、私のアプローチは、クラス ( ResourceManager_t
) のコンストラクターですべてのパラメーターを取得し、マップに新しいリソースを追加するたびに、そのリソースを追加できるかどうかを確認することでした。
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