假设我正在使用基于策略的模板设计模式(请参阅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 ?
感谢任何帮助:)