Ale*_*dre 5 c++ implementation templates
我发现下面的代码非常难以阅读,我写了它!有没有
ClassName::member_function_name为每个实现的成员函数?我在这方面找到了Java DRYer.你不要到处重复类名.谢谢!
template <class KeyType, class ObjectType>
class Vertex
{
private:
KeyType key;
const ObjectType* object;
public:
Vertex(const KeyType& key, const ObjectType& object);
const KeyType getKey();
};
template <class KeyType, class ObjectType>
class Graph
{
private:
map<KeyType, Vertex<KeyType, ObjectType> > vertexes;
public:
const Vertex<KeyType, ObjectType>& createVertex(const KeyType& key, const ObjectType& object);
};
template <class KeyType, class ObjectType>
Vertex<KeyType, ObjectType>::Vertex(const KeyType& objectKey, const ObjectType& newObject)
{
key = objectKey;
object = &newObject;
};
template <class KeyType, class ObjectType>
const KeyType Vertex<KeyType, ObjectType>::getKey()
{
return key;
};
template <class KeyType, class ObjectType>
const Vertex<KeyType, ObjectType>& Graph<KeyType, ObjectType>::createVertex(const KeyType& key, const ObjectType& object)
{
Vertex<KeyType, ObjectType> *vertex = new Vertex<KeyType, ObjectType>(key, object);
vertexes.insert(make_pair(vertex->getKey(), *vertex));
return *vertex;
};
Run Code Online (Sandbox Code Playgroud)
既然这是一个模板,为什么不在类体内定义成员函数呢?
无论如何,代码需要在编译单元中可用以进行实例化,因此您不会因将声明与定义分离而获得任何编译时间加速,并且编译器现在足够聪明,可以自行决定是否需要内联。