简体   繁体   English

CPP模板参数

[英]CPP Template Parameter

What's the consistency of the following codes:-以下代码的一致性是什么:-

TMAP.h TMAP.h

#include <algorithm>
#include <map>

template <class K, class V>
class TMAP
{ 
private:
    std::map <K,V>  map_K_V;

public:
    bool key_exists(const K& key) { return map_K_V.count( key ) > 0; }

    bool insert(const K& key, const V& value)
    {
        if (!key_exists(key))
        {
            if (map_K_V.insert( std::make_pair( key, value ) ).second)
            {
                return true;
            }
        }
        return false;
    }

    V get_value(const K& key)
    {
        return map_K_V[ key ];
    }
};

Template just like std::map , just more organized for other uses.模板就像std::map ,只是为了其他用途更有条理。

main.cpp主程序

#include <iostream>
#include "TMAP.h"

class A;

TMAP< std::string, A* > map_cntr;

class A
{
  public:
    A( std::string nm )
    {
      name = nm;
      std::cout << "A: " << name << ", object created." << std::endl;
    }

    ~A()
    {
      std::cout << "A: " << name << ", object destroyed." << std::endl;
    }

    void printName()
    {
      std::cout << "A: printName - " << name << std::endl;
    }

    void setName( std::string nm )
    {
        name = nm;
    }

  private:
    std::string name;
};

int main() {
    // Setting
    A* obj1 = new A( "obj1" );
    map_cntr.insert( "obj1", obj1 );
    obj1->printName();

    A* obj2 = new A( "obj2" );
    map_cntr.insert( "obj2", obj2 );
    obj2->printName();

    // Getting
    A* obj1_cpy;
    std::string obj1_name = "obj1";

    if (map_cntr.key_exists(obj1_name))
    {
        obj1_cpy = map_cntr.get_value(obj1_name);
        obj1_cpy->printName();
        obj1_cpy->setName("OBJ1");
        obj1_cpy->printName();
    }
}

Outputs:输出:

A: obj1, object created.  
A: printName - obj1  
A: obj2, object created.  
A: printName - obj2  
A: printName - obj1  
A: printName - OBJ1  

Outputs are as expected.输出符合预期。 Besides I've heard somewhere that using std::string as template parameter is not ideal just like in the above case somewhat relating to memory or pointer.此外,我在某处听说使用std::string作为模板参数并不理想,就像在上面的情况下与内存或指针有关。 Is it fair?公平吗?

It is std::map<const char*, Value> which is "problematic" , as it compare only pointers and not C-string content.它是std::map<const char*, Value>“有问题的” ,因为它只比较指针而不是 C 字符串内容。

Using std::map<std::string, Value> is fine.使用std::map<std::string, Value>很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM