具有成员函数模板的类模板,该成员函数模板的模板参数不是函数参数

时间:2018-07-08 14:33:58

标签: c++ c++11 templates

我正在实现代码以交换TCP消息,并且在this stackoverflow posting中遇到了一种有趣的消息构造方法。它使用一种工厂模式,其中要创建的对象类型已在工厂中注册。注册函数是成员模板,其模板参数是要创建的对象的类型,而不是函数本身的参数(这是相应的整数标识符)。

/**
* A class for creating objects, with the type of object created based on a key
* 
* @param K the key
* @param T the super class that all created classes derive from
*/
template<typename K, typename T>
class Factory { 
private:
    typedef T *(*CreateObjectFunc)();
    /**
    * A map keys (K) to functions (CreateObjectFunc)
    * When creating a new type, we simply call the function with the required key
    */
    std::map<K, CreateObjectFunc> mObjectCreator;

    /**
    * Pointers to this function are inserted into the map and called when creating objects
    *
    * @param S the type of class to create
    * @return a object with the type of S
    */
    template<typename S> 
    static T* createObject(){ 
        return new S(); 
    }

    //skip a bunch of code... 
public:
    /**
    * Registers a class to that it can be created via createObject()
    *
    * @param S the class to register, this must ve a subclass of T
    * @param id the id to associate with the class. This ID must be unique
    */ 
    template<typename S> 
    void registerClass(K id){ 
      if (mObjectCreator.find(id) != mObjectCreator.end()){ 
        //your error handling here
      }
      /*Note: I removed the explicit template parameters from the
       *call to std::make_pair() in the original code referenced in
       *text above since it caused complilation errors. */
      mObjectCreator.insert( std::make_pair(id, &createObject<S> ) ); 
    }
 }

我看不到要创建的类型()是如何注册的,因为它的类型不是注册函数的参数,因此无法从这些参数中推论得出。这是代码中的问题,还是我需要以某种方式声明该函数?

1 个答案:

答案 0 :(得分:0)

@IgorTandetnik在评论中提供了我自己的问题的答案。

解决方案是使用模板函数名称和带括号的自变量之间的普通括号,将模板参数简单地传递给模板函数:

<input type="text" value="x1" id="x1" style="display: none"><input type="text" value="x2" id="x2" style="display: none">
<img src="http://via.placeholder.com/20x20/ff0000/000000?text=1" onclick="copy('x1')"/> <img src="http://via.placeholder.com/20x20/00ff00/000000?text=2" onclick="copy('x2')" />