使用模板而不是虚拟方法的管道模式
A pipe pattern using templates instead of virtual methods
我正在尝试创建没有虚拟方法的管道模式,以便 class C
的对象将调用对象 class B
的方法,将调用对象 class A
的方法,...(并通过不同的方法反向调用)
如果这可行,那么它将像管道模式一样运行,StartChain::next
调用 C::next
调用 B::next
调用 A::next
调用 EndChain::next
,并且prev
从 EndChain::prev
-> StartChain::prev
通过不同的结构。
但是-我想不出允许这种情况发生的正确语法。
template<typename P>
struct EndChain
{
P *p;
void next ()
{
}
void prev ()
{
p->prev();
}
} ;
template<typename N, typename P>
struct A
{
N *n;
P *p;
void next ()
{
n->next();
}
void prev ()
{
p->prev();
}
} ;
template<typename N, typename P>
struct B
{
N *n;
P *p;
void next ()
{
n->next();
}
void prev ()
{
p->prev();
}
} ;
template<typename N, typename P>
struct C
{
N *n;
P *p;
void next ()
{
n->next();
}
void prev ()
{
p->prev();
}
} ;
template<typename N>
struct StartChain
{
N *n;
void next ()
{
n->next();
}
void prev ()
{
}
} ;
因为using Chain = StartChain<C<B<A<EndChain<B<A< ...
显然不行。
让我们假设我们可以按照您想要的方式实例化这些模板,例如Start
-> A
-> End
.
中间,我们需要A
的实例化,具体来说
A<Start<*>, End<*>>
除了我们没有要放入 *
的类型,因为这是我们要实例化的类型。我们有一个没有基本情况的递归定义。
您要求的内容无法用 C++ 类型表达
这是……一段旅程。我什至不得不休息一下,然后回来真正理解我刚刚写的东西。
想法是每个管道节点(A
、B
、C
)都是一个带有一个类型参数的class模板。此参数包含有关整个管道的信息,并且是节点 class 也必须继承的策略。由于我们不想陷入无限递归,我们将节点类型作为模板处理,直到必要时才实例化它们(这是在阶段 2 查找中,所有内容都已正确定义)。出发吧:
首先我们定义一组工具,一些简单的元函数:
// Stores a class template to be instantiated later
template <template <class...> class T>
struct tlift {
// Instantiate the template
template <class... Args>
using apply = T<Args...>;
};
// Identity function
template <class T>
struct identity {
using type = T;
};
...和一组 class 模板及其功能集:
// Pack of class templates
template <template <class> class...>
struct tpack { };
// Get the Nth element
template <class Pack, std::size_t N>
struct tpack_at;
template <template <class> class P0, template <class> class... P, std::size_t N>
struct tpack_at<tpack<P0, P...>, N> : tpack_at<tpack<P...>, N - 1> { };
template <template <class> class P0, template <class> class... P>
struct tpack_at<tpack<P0, P...>, 0> {
using type = tlift<P0>;
};
// Get the size of the pack
template <class Pack>
struct tpack_size;
template <template <class> class... P>
struct tpack_size<tpack<P...>>
: std::integral_constant<std::size_t, sizeof...(P)> { };
请注意,由于模板不能裸露,tpack_at
return是一个包含实际模板的 tlift
。
然后是解决方案的核心:策略 class,非原创名称 Context
。首先,我们四处看看我们的邻居是谁:
// Base class and template parameter for pipeline nodes
template <class Pipeline, std::size_t Index>
struct Context {
// Type of the previous node, or void if none exists
using Prev = typename std::conditional_t<
Index == 0,
identity<tlift<std::void_t>>,
tpack_at<Pipeline, Index - 1>
>::type::template apply<Context<Pipeline, Index - 1>>;
// Type of the next node, or void if none exists
using Next = typename std::conditional_t<
Index == tpack_size<Pipeline>::value - 1,
identity<tlift<std::void_t>>,
tpack_at<Pipeline, Index + 1>
>::type::template apply<Context<Pipeline, Index + 1>>;
这些有点复杂的 typedef 中的每一个都会检查我们是否是管道中的第一个(分别是最后一个)节点,然后检索包含我们之前(分别是下一个)节点的 tlift
。这个 tlift
然后用我们已经拥有的 Pipeline
和相邻的 Index
展开,以产生完整的节点类型。如果此邻居不存在,则 tlift
包含 std::void_t
,这将在展开时忽略其参数和 return void
.
完成这种体操后,我们可以为我们的两个邻居存储两个指针:
private:
Prev *_prev;
Next *_next;
注意:第一个和最后一个 Context
都包含一个未使用的 void *
到它们不存在的邻居。我没有花时间优化它们,但这也可以做到。
然后我们实现两个将被节点继承的函数,并允许它在它的邻居上调用prev
和next
。因为它没有增加复杂性,而且无论如何我都需要一个 if constexpr
的模板,所以我在混合中添加了参数转发:
// Call the previous node's prev() function with arguments
template <class... Args>
void callPrev(Args &&... args) {
if constexpr(!std::is_void_v<Prev>)
_prev->prev(std::forward<Args>(args)...);
}
// Call the next node's next() function with arguments
template <class... Args>
void callNext(Args &&... args) {
if constexpr(!std::is_void_v<Next>)
_next->next(std::forward<Args>(args)...);
}
最后,Context
的构造函数需要对所有节点的元组的引用,并将从中选择其邻居:
// Construction from the actual tuple of nodes
template <class... T>
Context(std::tuple<T...> &pipeline) {
if constexpr(std::is_void_v<Prev>) _prev = nullptr;
else _prev = &std::get<Index - 1>(pipeline);
if constexpr(std::is_void_v<Next>) _next = nullptr;
else _next = &std::get<Index + 1>(pipeline);
}
唯一剩下要做的就是将我们需要的怪异初始化包装到一个 maker 函数中:
template <template <class> class... Nodes, std::size_t... Idx>
auto make_pipeline(std::index_sequence<Idx...>) {
using Pack = tpack<Nodes...>;
std::tuple<Nodes<Context<Pack, Idx>>...> pipeline{{((void)Idx, pipeline)}...}; // (1)
return pipeline;
}
template <template <class Context> class... Nodes>
auto make_pipeline() {
return make_pipeline<Nodes...>(std::make_index_sequence<sizeof...(Nodes)>{});
}
注意 (1)
处的递归点,其中 pipeline
会将其自己的引用传递给各个节点的构造函数,以便它们各自将其转发给它们的 Context
。 ((void)Idx, pipeline)
技巧是让表达式依赖于模板参数包,这样我就可以实际打包扩展它。
最后一个节点可以这样定义:
template <class Context>
struct NodeA : Context {
// Forward the context's constructor, or implement yours
using Context::Context;
void prev() {
// Do something
Context::callPrev();
}
void next() {
// Do something
Context::callNext();
}
};
... 用法如下:
int main() {
auto pipeline = make_pipeline<NodeA, NodeB, NodeC>();
std::get<0>(pipeline).next(); // Calls the whole chain forward
std::get<2>(pipeline).prev(); // Calls the whole chain backwards
}
请注意,管道内的指针仍然有效,这要归功于从 make_pipeline
进行 return 时发生的复制省略。但是,您不应该进一步复制它(正确的防止复制留作练习)。
就这些了,伙计们。 See it live on Coliru
按照 Quentin 的回答使用完整的管道是可行的方法。
但是 prev
/next
对您的用法来说似乎是多余的,然后可以简化代码。
template <typename ... Nodes>
class pipeline
{
public:
explicit pipeline(const std::tuple<Nodes...>& nodes) : nodes(nodes) {}
template <typename ... Ts>
void traverse(Ts&&... args) {
std::apply([&](auto&&... flatNodes){ (flatNodes(args...), ...); }, nodes);
}
template <typename ... Ts>
void rev_traverse(Ts&&... args) {
rev_traverse_impl(std::index_sequence_for<Nodes...>(), std::forward<Ts>(args)...);
}
private:
template <typename ... Ts, std::size_t ... Is>
void rev_traverse_impl(std::index_sequence<Is...>, Ts&&...args)
{
constexpr auto size = sizeof...(Nodes);
(std::get<size - 1 - Is>(nodes)(args...), ...);
}
private:
std::tuple<Nodes...> nodes;
};
节点类似于:
class A
{
public:
A(/*...*/);
void operator()() const { /*..*/ }
};
和用法:
pipeline<A, B, B, C> p({A{}, B{0}, B{1}, C{}});
p.traverse();
p.rev_traverse();
甚至使用 lambda:
pipeline p(std::tuple(A{}, B{0}, B{1}, [](){ std::cout << "Lambda"; }));
我正在尝试创建没有虚拟方法的管道模式,以便 class C
的对象将调用对象 class B
的方法,将调用对象 class A
的方法,...(并通过不同的方法反向调用)
如果这可行,那么它将像管道模式一样运行,StartChain::next
调用 C::next
调用 B::next
调用 A::next
调用 EndChain::next
,并且prev
从 EndChain::prev
-> StartChain::prev
通过不同的结构。
但是-我想不出允许这种情况发生的正确语法。
template<typename P>
struct EndChain
{
P *p;
void next ()
{
}
void prev ()
{
p->prev();
}
} ;
template<typename N, typename P>
struct A
{
N *n;
P *p;
void next ()
{
n->next();
}
void prev ()
{
p->prev();
}
} ;
template<typename N, typename P>
struct B
{
N *n;
P *p;
void next ()
{
n->next();
}
void prev ()
{
p->prev();
}
} ;
template<typename N, typename P>
struct C
{
N *n;
P *p;
void next ()
{
n->next();
}
void prev ()
{
p->prev();
}
} ;
template<typename N>
struct StartChain
{
N *n;
void next ()
{
n->next();
}
void prev ()
{
}
} ;
因为using Chain = StartChain<C<B<A<EndChain<B<A< ...
显然不行。
让我们假设我们可以按照您想要的方式实例化这些模板,例如Start
-> A
-> End
.
中间,我们需要A
的实例化,具体来说
A<Start<*>, End<*>>
除了我们没有要放入 *
的类型,因为这是我们要实例化的类型。我们有一个没有基本情况的递归定义。
您要求的内容无法用 C++ 类型表达
这是……一段旅程。我什至不得不休息一下,然后回来真正理解我刚刚写的东西。
想法是每个管道节点(A
、B
、C
)都是一个带有一个类型参数的class模板。此参数包含有关整个管道的信息,并且是节点 class 也必须继承的策略。由于我们不想陷入无限递归,我们将节点类型作为模板处理,直到必要时才实例化它们(这是在阶段 2 查找中,所有内容都已正确定义)。出发吧:
首先我们定义一组工具,一些简单的元函数:
// Stores a class template to be instantiated later
template <template <class...> class T>
struct tlift {
// Instantiate the template
template <class... Args>
using apply = T<Args...>;
};
// Identity function
template <class T>
struct identity {
using type = T;
};
...和一组 class 模板及其功能集:
// Pack of class templates
template <template <class> class...>
struct tpack { };
// Get the Nth element
template <class Pack, std::size_t N>
struct tpack_at;
template <template <class> class P0, template <class> class... P, std::size_t N>
struct tpack_at<tpack<P0, P...>, N> : tpack_at<tpack<P...>, N - 1> { };
template <template <class> class P0, template <class> class... P>
struct tpack_at<tpack<P0, P...>, 0> {
using type = tlift<P0>;
};
// Get the size of the pack
template <class Pack>
struct tpack_size;
template <template <class> class... P>
struct tpack_size<tpack<P...>>
: std::integral_constant<std::size_t, sizeof...(P)> { };
请注意,由于模板不能裸露,tpack_at
return是一个包含实际模板的 tlift
。
然后是解决方案的核心:策略 class,非原创名称 Context
。首先,我们四处看看我们的邻居是谁:
// Base class and template parameter for pipeline nodes
template <class Pipeline, std::size_t Index>
struct Context {
// Type of the previous node, or void if none exists
using Prev = typename std::conditional_t<
Index == 0,
identity<tlift<std::void_t>>,
tpack_at<Pipeline, Index - 1>
>::type::template apply<Context<Pipeline, Index - 1>>;
// Type of the next node, or void if none exists
using Next = typename std::conditional_t<
Index == tpack_size<Pipeline>::value - 1,
identity<tlift<std::void_t>>,
tpack_at<Pipeline, Index + 1>
>::type::template apply<Context<Pipeline, Index + 1>>;
这些有点复杂的 typedef 中的每一个都会检查我们是否是管道中的第一个(分别是最后一个)节点,然后检索包含我们之前(分别是下一个)节点的 tlift
。这个 tlift
然后用我们已经拥有的 Pipeline
和相邻的 Index
展开,以产生完整的节点类型。如果此邻居不存在,则 tlift
包含 std::void_t
,这将在展开时忽略其参数和 return void
.
完成这种体操后,我们可以为我们的两个邻居存储两个指针:
private:
Prev *_prev;
Next *_next;
注意:第一个和最后一个 Context
都包含一个未使用的 void *
到它们不存在的邻居。我没有花时间优化它们,但这也可以做到。
然后我们实现两个将被节点继承的函数,并允许它在它的邻居上调用prev
和next
。因为它没有增加复杂性,而且无论如何我都需要一个 if constexpr
的模板,所以我在混合中添加了参数转发:
// Call the previous node's prev() function with arguments
template <class... Args>
void callPrev(Args &&... args) {
if constexpr(!std::is_void_v<Prev>)
_prev->prev(std::forward<Args>(args)...);
}
// Call the next node's next() function with arguments
template <class... Args>
void callNext(Args &&... args) {
if constexpr(!std::is_void_v<Next>)
_next->next(std::forward<Args>(args)...);
}
最后,Context
的构造函数需要对所有节点的元组的引用,并将从中选择其邻居:
// Construction from the actual tuple of nodes
template <class... T>
Context(std::tuple<T...> &pipeline) {
if constexpr(std::is_void_v<Prev>) _prev = nullptr;
else _prev = &std::get<Index - 1>(pipeline);
if constexpr(std::is_void_v<Next>) _next = nullptr;
else _next = &std::get<Index + 1>(pipeline);
}
唯一剩下要做的就是将我们需要的怪异初始化包装到一个 maker 函数中:
template <template <class> class... Nodes, std::size_t... Idx>
auto make_pipeline(std::index_sequence<Idx...>) {
using Pack = tpack<Nodes...>;
std::tuple<Nodes<Context<Pack, Idx>>...> pipeline{{((void)Idx, pipeline)}...}; // (1)
return pipeline;
}
template <template <class Context> class... Nodes>
auto make_pipeline() {
return make_pipeline<Nodes...>(std::make_index_sequence<sizeof...(Nodes)>{});
}
注意 (1)
处的递归点,其中 pipeline
会将其自己的引用传递给各个节点的构造函数,以便它们各自将其转发给它们的 Context
。 ((void)Idx, pipeline)
技巧是让表达式依赖于模板参数包,这样我就可以实际打包扩展它。
最后一个节点可以这样定义:
template <class Context>
struct NodeA : Context {
// Forward the context's constructor, or implement yours
using Context::Context;
void prev() {
// Do something
Context::callPrev();
}
void next() {
// Do something
Context::callNext();
}
};
... 用法如下:
int main() {
auto pipeline = make_pipeline<NodeA, NodeB, NodeC>();
std::get<0>(pipeline).next(); // Calls the whole chain forward
std::get<2>(pipeline).prev(); // Calls the whole chain backwards
}
请注意,管道内的指针仍然有效,这要归功于从 make_pipeline
进行 return 时发生的复制省略。但是,您不应该进一步复制它(正确的防止复制留作练习)。
就这些了,伙计们。 See it live on Coliru
按照 Quentin 的回答使用完整的管道是可行的方法。
但是 prev
/next
对您的用法来说似乎是多余的,然后可以简化代码。
template <typename ... Nodes>
class pipeline
{
public:
explicit pipeline(const std::tuple<Nodes...>& nodes) : nodes(nodes) {}
template <typename ... Ts>
void traverse(Ts&&... args) {
std::apply([&](auto&&... flatNodes){ (flatNodes(args...), ...); }, nodes);
}
template <typename ... Ts>
void rev_traverse(Ts&&... args) {
rev_traverse_impl(std::index_sequence_for<Nodes...>(), std::forward<Ts>(args)...);
}
private:
template <typename ... Ts, std::size_t ... Is>
void rev_traverse_impl(std::index_sequence<Is...>, Ts&&...args)
{
constexpr auto size = sizeof...(Nodes);
(std::get<size - 1 - Is>(nodes)(args...), ...);
}
private:
std::tuple<Nodes...> nodes;
};
节点类似于:
class A
{
public:
A(/*...*/);
void operator()() const { /*..*/ }
};
和用法:
pipeline<A, B, B, C> p({A{}, B{0}, B{1}, C{}});
p.traverse();
p.rev_traverse();
甚至使用 lambda:
pipeline p(std::tuple(A{}, B{0}, B{1}, [](){ std::cout << "Lambda"; }));