gpt4 book ai didi

c++ - 函数中的模板模板替换

转载 作者:搜寻专家 更新时间:2023-10-31 00:12:37 24 4
gpt4 key购买 nike

我正在实现自己的 UniquePtr,我想测试它是否具有与 std::unique_ptr 相同的接口(interface)。所以我写了一个函数:

class A
{
A() { }
~A() { }
};

class B
{
B() { }
~B() { }
};


template <template <typename Type> class UPtr>
void test_unique_ptr_interface()
{
UPtr<A> p1(new A);
{
UPtr<A> p2(std::move(p1));
p1 = std::move(p2);
}

UPtr<B> p1(new B);
{
UPtr<B> p2(std::move(p1));
p1 = std::move(p2);
}
...
}

然后我想这样调用它:

test_unique_ptr_interface<std::unique_ptr>(); 
test_unique_ptr_interface<UniquePtr>();

第一个调用测试 std::unique_ptr 通过测试,因此我正在测试正确的接口(interface)。第二个调用测试我自己的 UniquePtr 实现是否可以作为替代品。 test_unique_ptr_interface 函数会长很多,我只是贴了一个简单的例子。

但是,我得到一个错误:

error: no matching function for call to ‘test_unique_ptr_interface()’
test_unique_ptr_interface<std::unique_ptr>();

我应该如何声明 test_unique_ptr_interface() 函数以便编译?

最佳答案

查找 declaration of std::unique_ptr :

template <class T, class Deleter = std::default_delete<T>>
class unique_ptr;

这是一个带有 2 个模板参数的类模板。要准确复制它,您必须更改您的类模板以匹配,并更改测试函数:

template <template <typename, typename> class UPtr>
void test_unique_ptr_interface()
{
// ...
}

另一种方法是使模板模板参数可变:

template <template <typename... > class UPtr>
void test_unique_ptr_interface()
{
// ...
}

这将允许您的类只保留一个模板参数。请注意,它不会是 std::unique_ptr 的完全替代品,不过。

关于c++ - 函数中的模板模板替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29655391/

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