Pat*_*ght 2 c++ templates smart-pointers c++17
我经常编写具有类似于以下签名的工厂:
std::unique_ptr<AbstractType> createUnique(IDType id);
std::shared_ptr<AbstractType> createShared(IDType id);
Run Code Online (Sandbox Code Playgroud)
前者会做类似的事情:
switch (id)
{
case kID1:
return std::make_unique<Type1>();
}
Run Code Online (Sandbox Code Playgroud)
而后者
switch (id)
{
case kID1:
return std::make_shared<Type1>();
}
Run Code Online (Sandbox Code Playgroud)
那么,这两个函数之间的唯一区别是使用的“make”函数(make_shared或make_unique)和返回类型(shared_ptr或unique_ptr)。这会导致代码重复。
我想知道如何编写一个create接受指针类型和“make”函数类型并使用它们的模板化函数。就像是:
template <typename PTR, typename MAKE>
PTR create(IDType id)
{
switch (id)
{
case kID1:
return MAKE<Type1>();
}
}
Run Code Online (Sandbox Code Playgroud)
我知道以上不是有效的代码。
另外,我知道 astd::shared_ptr可以从 an 创建,std::unique_ptr反之亦然,但我这个工厂将用于不同的应用程序,其中一个可能使用 a shared_ptr,另一个可能使用unique_ptr. 这样,代码就可以重复使用,而且对于特定的用例也很有效。
我的建议是,只有单一返回类型std::unique_ptr<AbstractType>. 如果你这样做,那么你可以使用该函数,std::unique_ptr如std::shared_ptr
auto my_ptr = createInterface(id);
Run Code Online (Sandbox Code Playgroud)
其中my_ptr有一个unique_ptr或
std::shared_ptr<AbstractType> my_ptr = createInterface(id);
Run Code Online (Sandbox Code Playgroud)
现在返回的值unique_ptr被转换为shared_ptr.