gpt4 book ai didi

c++ - 特化 std::make_shared

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:00:27 24 4
gpt4 key购买 nike

我有一个具有严格对齐要求(由于使用了 AVX 操作)的类型,它大于平台默认对齐方式。

为了简化此类的使用,我想专门化 std::make_shared 以始终为该类型使用合适的分配器。

像这样:

namespace std{
template<class... Args> inline
auto make_shared<X, Args...>(Args&&... args){
return std::allocate_shared(allocator_type<X, 32>, std::forward<Args>(args)...);
}
}

我的问题是,标准允许这样做吗?它会按预期工作吗?

最佳答案

来自 N4140 [namespace.std]/1(强调我的):

The behavior of a C++program is undefined if it adds declarations or definitions to namespace std or to a namespace within namespace std unless otherwise specified. A program may add a template specialization for any standard library template to namespace std only if the declaration depends on a user-defined type and the specialization meets the standard library requirements for the original template and is not explicitly prohibited.

由于您要添加依赖于用户定义类型的模板特化,因此这是 std 命名空间的有效扩展。

但是,正如@dyp 所指出的,您不能部分特化函数模板。您最好的选择是显式指定 X 构造函数的参数(失去完美转发),或者只编写一个 make_shared_x 函数(失去一致性)。

关于c++ - 特化 std::make_shared,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31473756/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com