gpt4 book ai didi

c++ - 使用 SFINAE 有条件地解析分配器成员

转载 作者:太空狗 更新时间:2023-10-29 21:33:25 25 4
gpt4 key购买 nike

我正在为列表数据结构编写构造函数。

template <class T, class Allocator = std::allocator<T>>
class list {

...
}

该类采用 Allocator 模板参数,如果未提供,则默认为 std::allocator。由于 C++11 分配器可能具有状态,因此默认构造函数也采用分配器对象。

//    *** CONSTRUCTORS ***
explicit list(const Allocator& alloc = Allocator()): alloc_(alloc), head_(nullptr), tail_(nullptr), size_(0) {
if(std::is_same<Allocator, customAllocator<T>>::value) {
std::cout << "****" << std::endl;
std::cout << alloc.member_ << std::endl;
std::cout << alloc_.member_ << std::endl;
std::cout << "****" << std::endl;
}
}

当提供包含“member_”的自定义分配器时,以下行将无故障执行。

然而,当 std::allocator 被传递时,编译器可以理解地提示分配器中没有成员 'member_'。

然而,有没有一种方法可以在提供自定义分配器时打印 std::cout 行,而在提供 std::allocator 时不打印(或任何不带“member_”的分配器)是否提供?

谢谢

最佳答案

您的问题是在 C++17 中引入的典型问题 if constexpr

 if constexpr (std::is_same<Allocator, customAllocator<T>>::value) {
std::cout << "****" << std::endl;
std::cout << alloc.member_ << std::endl;
std::cout << alloc_.member_ << std::endl;
std::cout << "****" << std::endl;
}

在 C++17 之前,if constexpr不可用,所以 std::cout << alloc.member_也在 std::is_same 时编译测试是错误的。

所以你必须以某种方式开发两个不同的函数:一个用于 customAllocator一个给其他人。

我想你可以尝试如下操作(注意:代码未经测试)

   template <typename T>
void printMember (customAllocator<T> const & a)
{
std::cout << "****" << std::endl;
std::cout << alloc.member_ << std::endl;
std::cout << alloc_.member_ << std::endl;
std::cout << "****" << std::endl;
}

template <typename A>
void printMember (A const &)
{ }

explicit list(const Allocator& alloc = Allocator())
: alloc_(alloc), head_(nullptr), tail_(nullptr), size_(0)
{ printMember(alloc); }

如果你愿意,你也可以用member_为分配器写一个函数。成员和其他人。

如下(注意:代码未测试)

   template <typename A>
auto printMember (A const & a, int)
-> decltype( a.member_, void() )
{
std::cout << "****" << std::endl;
std::cout << alloc.member_ << std::endl;
std::cout << alloc_.member_ << std::endl;
std::cout << "****" << std::endl;
}

template <typename A>
void printMember (A const &, long)
{ }

explicit list(const Allocator& alloc = Allocator())
: alloc_(alloc), head_(nullptr), tail_(nullptr), size_(0)
{ printMember(alloc, 0); }

关于c++ - 使用 SFINAE 有条件地解析分配器成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51096718/

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