请记住,std::any 和 std::function 等类型擦除工具仅公开接口
他们承诺仅此而已:std::any 封装了复制能力,仅此而已,因此您不能
比较相等/散列 std::any 对象。使用额外的std::function 只是为了存储
operator< 很麻烦(基本上每种类型都使用两个 vtable),你最好
使用手卷式擦除。
此外,根据您的要求,您必须特例 const char* 或 const char(&)[N]
参数,因为您希望它们存储为std::string,并且还用于它们的比较运算符。这
还解决了您的“使用std::any 中的参考成员存储std::tuple”问题。 (有关更多讨论,请参阅编辑说明 #2。)
您的神螺栓链接中的代码在某些地方不正确,尤其是您传递的代码
T 的构造函数的参数构造一个std::any(缺少前面的std::in_place_type<T>,
就是)。
为方便起见,以下实现使用 C++20,但它可以在
旧标准稍作修改。
编辑 #1:修复了未初始化的初始哈希值,对我来说真的是一个菜鸟错误。
编辑 #2:是的,特殊情况 const char* 的技巧不是很好,它会阻止使用 const char* 的 c'tors 工作。您可以将其重写为“仅衰减每个参数,不对const char* 或const char(&)[N] 采取任何特殊操作”,这将适用于所有c'tors。但这也仅在您传入字符串文字时才有效,否则您可能会在哈希映射中存储一个悬空指针。如果您通过std::string 指定您真正想要传递引用的每个位置(例如,通过使用像"hello"s 这样的UDL 或显式构造std::string),那么这种方法可能是可以的。
AFAIK 您无法获取 c'tors 的参数类型,因为 C++ 明确不允许获取 c'tors 的地址,并且如果您无法形成指向成员函数的指针,则无法对其进行模板技巧。此外,重载决议可能是实现这一目标的另一个障碍。
编辑#3:我没有注意到会有不可复制的对象缓存。在这种情况下,std::any 没有用,因为它只能存储可复制的对象。使用类似类型的擦除技术也可以存储不可复制的对象。我的实现只是使用std::unique_ptr 来存储已擦除的键和值,强制它们存储在堆上。这个简单的方法甚至支持不可复制的和不可移动的类型。如果需要 SBO,则必须使用更复杂的方法来存储类型擦除的对象。
#include <iostream>
#include <unordered_map>
#include <type_traits>
// Algorithm taken from boost
template <typename T>
void hash_combine(std::size_t& seed, const T& value)
{
static constexpr std::size_t golden_ratio = []
{
if constexpr (sizeof(std::size_t) == 4)
return 0x9e3779b9u;
else if constexpr (sizeof(std::size_t) == 8)
return 0x9e3779b97f4a7c15ull;
}();
seed ^= std::hash<T>{}(value) + golden_ratio +
std::rotl(seed, 6) + std::rotr(seed, 2);
}
class Factory
{
public:
template <typename T, typename... Args>
const T& get(Args&&... args)
{
Key key = construct_key<T, Args...>(static_cast<Args&&>(args)...);
if (const auto iter = cache_.find(key); iter != cache_.end())
return static_cast<ValueImpl<T>&>(*iter->second).value;
Value value = key->construct();
const auto [iter, emplaced] = cache_.emplace(
std::piecewise_construct,
// Move the key, or it would be forwarded as an lvalue reference in the tuple
std::forward_as_tuple(std::move(key)),
// Also the value, remember that this tuple constructs a std::any, not a T
std::forward_as_tuple(std::move(value))
);
return static_cast<ValueImpl<T>&>(*iter->second).value;
}
private:
struct ValueModel
{
virtual ~ValueModel() noexcept = default;
};
template <typename T>
struct ValueImpl final : ValueModel
{
T value;
template <typename... Args>
explicit ValueImpl(Args&&... args): value(static_cast<Args&&>(args)...) {}
};
using Value = std::unique_ptr<ValueModel>;
struct KeyModel
{
virtual ~KeyModel() noexcept = default;
virtual std::size_t hash() const = 0;
virtual bool equal(const KeyModel& other) const = 0;
virtual Value construct() const = 0;
};
template <typename T, typename... Args>
class KeyImpl final : public KeyModel
{
public:
template <typename... Ts>
explicit KeyImpl(Ts&&... args): args_(static_cast<Ts&&>(args)...) {}
// Use hash_combine to get a hash
std::size_t hash() const override
{
std::size_t seed{};
std::apply([&](auto&&... args)
{
(hash_combine(seed, args), ...);
}, args_);
return seed;
}
bool equal(const KeyModel& other) const override
{
const auto* ptr = dynamic_cast<const KeyImpl*>(&other);
if (!ptr) return false; // object types or parameter types don't match
return args_ == ptr->args_;
}
Value construct() const override
{
return std::apply([](const Args&... args)
{
return std::make_unique<ValueImpl<T>>(args...);
}, args_);
}
private:
std::tuple<Args...> args_;
};
using Key = std::unique_ptr<KeyModel>;
using Hasher = decltype([](const Key& key) { return key->hash(); });
using KeyEqual = decltype([](const Key& lhs, const Key& rhs) { return lhs->equal(*rhs); });
std::unordered_map<Key, Value, Hasher, KeyEqual> cache_;
template <typename T, typename... Args>
static Key construct_key(Args&&... args)
{
constexpr auto decay_or_string = []<typename U>(U&& arg)
{
// convert to std::string if U decays to const char*
if constexpr (std::is_same_v<std::decay_t<U>, const char*>)
return std::string(arg);
// Or just decay the parameter otherwise
else
return std::decay_t<U>(arg);
};
using KeyImplType = KeyImpl<T, decltype(decay_or_string(static_cast<Args&&>(args)))...>;
return std::make_unique<KeyImplType>(decay_or_string(static_cast<Args&&>(args))...);
}
};
struct IntRes
{
int id;
explicit IntRes(const int id): id(id) {}
};
struct StringRes
{
std::string id;
explicit StringRes(std::string id): id(std::move(id)) {}
};
int main()
{
Factory factory;
std::cout << factory.get<IntRes>(42).id << std::endl;
std::cout << factory.get<StringRes>("hello").id << std::endl;
}