0

假设我正在使用基于策略的模板设计模式(请参阅https://en.wikipedia.org/wiki/Modern_C%2B%2B_Design)。

我遇到了一些与如何使用std::make_shared(或就此而言 std::make_unique)创建新类型Bar相关的问题,该类型具有一些可选的模板参数。
如果我不想更改默认策略,那没问题,简单的行就可以了:

auto bar = std::make_unique<Bar>();

但是,如果我希望 Bar 接受不同的“策略”作为模板参数,我该如何将它们传递给 std::make_unique ?

尝试了以下(没有运气):

auto bar = std::make_unique<Bar<Policy2, Policy3>>();

或者:

auto bar = std::make_unique<Bar>(Policy2, Policy3);

以下是一些示例代码来演示该问题:

// Bar.hpp
template<PolicyConcept1 T = policy1_default, PolicyConcept2 V = policy2_default>
class Bar
{
public:
    Bar();

private:
    // Data Members
    std::unique_ptr<T> _policy1;
    std::unique_ptr<V> _policy2;    
};

// bar.cpp
#include "bar.hpp"

template<PolicyConcept1 T, PolicyConcept2 V>
Bar<T, V>::Bar() :
_policy1{ std::make_unique<T>() },
_policy2{ std::make_unique<V>()}
{

}

// Foo.hpp
template<PolicyConcept1 T = policy1_default, PolicyConcept2 V = policy2_default>
class Foo
{
public:
    Foo();

private:
    // Data Members
    std::unique_ptr<Bar> _bar;  

};

#include "Foo.hpp"


template<PolicyConcept1 T, PolicyConcept2 V>
Foo<T, V>::Foo() :
  // problem is here, how do I change the default policy and forward it into std::make_unique ??
    _bar{ std::make_unique<bar>() }
{

}

问题在 Foo CTOR 的初始化程序内部:如何将 T & V 模板参数转发到 std::make_unique ?

感谢任何帮助:)

4

1 回答 1

0

想通了。结果是语法:

auto bar = std::make_unique<Bar<Policy2, Policy3>>();

毕竟可以工作(在 C++20 上,使用 MSVC v16.10.2)。

它需要以下声明才能工作:

std::unique_ptr<Bar<T,V>> _bar;

此外,我还必须在 CPP 上提供这个(以避免链接器错误):

template class Bar<concrete_policy1, concrete_policy2>;
于 2021-09-17T19:13:48.320 回答