gsf*_*gsf 4 c++ policy templates class
我是新来的.我正在创建一个政策说:
template <typename T,
typename P1 = Policy1<T>,
typename P2 = Policy2<T> >
{
...
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是某些策略有参数,当它们编译时它就可以了
template <typename T,
typename P1 = Policy1<T, size_t N>,
typename P2 = Policy2<T> >
Run Code Online (Sandbox Code Playgroud)
但是当它们是运行时我不确定提供策略类对象的最佳方式是什么......或者这不再是策略模式?
你可以有一个工厂的政策:) 编辑见下面添加
您可以像标准库那样做:
#include <string>
struct DummyPolicy { };
template <typename>
struct Policy1 { Policy1(int, std::string) { } };
template <typename T,
typename P1 = Policy1<T> >
struct X
{
X(P1 p1 = {}) : _policy1(std::move(p1)) { }
private:
P1 _policy1;
};
Run Code Online (Sandbox Code Playgroud)
并使用它
int main()
{
X<int, DummyPolicy> no_questions_asked;
X<int> use_params({42, "hello world"});
}
Run Code Online (Sandbox Code Playgroud)
使用C++ 03或显式构造函数显然可以拼写出来:
X<int> use_params(Policy1<int>(42, "hello world"));
Run Code Online (Sandbox Code Playgroud)
在科利鲁看到它
这是一个显示工厂方法的更新:
#include <string>
namespace details
{
template <typename PolicyImpl>
struct PolicyFactory
{
static PolicyImpl Create() {
return {};
}
};
}
template <typename>
struct Policy2 { Policy2(double) { } };
template <typename T,
typename P1 = Policy2<T> >
struct X
{
X() : _policy1(details::PolicyFactory<P1>::Create()) {}
X(P1 p1) : _policy1(std::move(p1)) { }
private:
P1 _policy1;
};
///// supply a factor, possibly local to a TU:
namespace details
{
template <typename T>
struct PolicyFactory<Policy2<T> > {
static Policy2<T> Create() {
return Policy2<T>(3.14);
}
};
}
int main()
{
// with a factory:
X<std::string, Policy2<std::string> > no_params_because_of_factory;
}
Run Code Online (Sandbox Code Playgroud)
注意
模板中的策略用于在编译时自定义类,而不是在运行时(策略调整实例的类型,并且在C++中无法在运行时决定类型).
运行时的并行通常称为"依赖注入",例如,通过传递实例将委派操作的已构造对象.
| 归档时间: |
|
| 查看次数: |
847 次 |
| 最近记录: |