[英]Alternatives for std::enable_if and explicit overloading for template template parameters
请考虑以下设置:
template< typename Held >
class Node{
//...
};
template< typename Held >
class vNode{
//...
};
template <typename... Graphs>
class Branch{
//...
};
template <typename...> class Graph; // undefined
template<
typename node_t
> class Graph< node_t >{ //specialization for an ending node
//...
};
template<
typename node_t,
typename... Graphs
> class Graph< node_t, Branch< Graphs...> >{ //specialization for a mid-graph node
//...
};
template<
template <typename> class node_t,
typename Held
> void f( Graph< Node<Held> > ) {
//stuff A on a node
}
template<
template <typename> class node_t,
typename Held
> void f( Graph< const Node<Held> > ) {
//stuff A on a const node
}
template<
template <typename> class node_t,
typename Held
> void f( Graph< vNode<Held> > ) {
//stuff B on a virtual node
}
template<
template <typename> class node_t,
typename Held
> void f( Graph< const vNode<Held> > ) {
//stuff B on a virtual const node
}
template<
template <typename> class node_t,
typename Held,
typename... Graphs
> void f( Graph< Node<Held>, Branch<Graphs...>> ) {
//stuff C on a node with a branch
}
template<
template <typename> class node_t,
typename Held,
typename... Graphs
> void f( Graph< const Node<Held>, Branch<Graphs...> > ) {
//stuff C on a const node with a branch
}
template<
template <typename> class node_t,
typename Held,
typename... Graphs
> void f( Graph< vNode<Held>, Branch<Graphs...> > ) {
//stuff D on a virtual node with a branch
}
template<
template <typename> class node_t,
typename Held,
typename... Graphs
> void f( Graph< const vNode<Held>, Branch<Graphs...> > ) {
//stuff D on a virtual const node with a branch
}
换句话说-我正在创建代表图形的类型。 节点可以是普通的,也可以是虚拟的,const和非const。 图可以包含一个节点,也可以包含图的一个节点和一个分支。
当我创建一个函数f
我希望它是const中立的(在图中节点的const版本和非const版本上执行相同的操作,但在分支图和非分支图上执行不同的操作)。 我一定要吗:
使用std::enable_if
骇客?
有没有更聪明的解决方案来使f
接受const和non-const节点?
不用使用模板模板参数并且具有大量的超载,只需使用类型模板参数即可:
template<class T> void f( Graph<T> ) { /*...*/ }
T
将推导T
为Node<Foo>
, vNode<Foo>
或const Node<Foo>
等。 如果Node
vs vNode
重要,则始终可以使用简单的特征类提取节点的类型。 同样,可以将static_assert
与trait类一起使用,以确保T
是Node
或vNode
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.