Can I rely on template type?
I am looking into working code from Game AI by example book and there is a part I do not understand.
There is
template <class node_type, class edge_type>
class SparseGraph
{ ... };
and
int SparseGraph<node_type, edge_type>::AddNode(node_type node)
{
if (node.Index() < (int)m_Nodes.size())
...
}
How can be node.Index()
called?
There also i开发者_运维百科s class
class GraphNode
{
public:
...
int Index()const{return m_iIndex;}
....
};
and graph is created with this class
typedef SparseGraph<GraphNode, GraphEdge> NavGraph;
NavGraph * m_pGraph;
so I understand what node.Index()
does, BUT
how can I call node.Index()
while there is no guarantee that node_type
is GraphNode
.
what if node_type
is not GraphNode
??
Hope you understand my question.
If node_type
is not GraphNode, then your compiler will smack you and throw an error. However, if your class depends on the Index
function, then you should document it as a requirement and any replacement for GraphNode must provide it, probably with some expected semantics.
Duck typing.
There is also a convenient feature in C++ called SFINAE (Substitution Failure Is Not An Error) that will remove a template from the considered candidates if an expression dependent on the type would not compile with the particular concrete type.
A way of restricting the types accepted as template parameters based on supported operations, i.e. Concepts, was originally planned for C++0x but scrapped due to committee disagreement on its design. You can still find early implementations in some forks of GCC and Boost also has a concepts library. See here.
C++ template functions are instantiated at point of use. i.e., it will paste in the types you specify when you specify them, and not sooner. At that point, if the type you specify does not have an Index
member function, the compilation will fail.
精彩评论