非模板类的构造函数中的模板参数

flo*_*eng 2 c++ templates

我想要一个非模板类的构造函数,它由一个类型模板化.有人可以帮忙吗?

class A
{
    public:
    static int GetId(){ return 5;}
};

class B
{
    public:
    B(int id){ _id = id;}

    template<typename T> 
    B() {_id = T::GetId();}

    template<typename T>
    static B* newB() {return new B(T::GetId());}

    private:
    int _id;
};

void doSome()
{
    B* p1 = B::newB<A>(); //works
    B* p2 = new B<A>(); //doesn't compile -- ">>B<< is no template"
}
Run Code Online (Sandbox Code Playgroud)

Rei*_*ica 5

构造函数模板的所有模板参数都必须是可推导的(或者具有默认参数),因为没有用于将模板参数显式传递给构造函数的语法(如您所知).

有几种可能的方法:

  1. 提供类似构造函数的函数模板.你已经这样做了newB,没有必要强制动态分配:

    template <class T>
    B create() { return B(T::GetId()); }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 提供标记类型并通过以下方式对consturctor进行参数化:

    template <class T>
    struct Tag {};
    
    class B
    {
    public:
      template <class T>
      B(Tag<T>) : _id(T::GetId()) {}
    };
    
    //usage:
    B b(Tag<A>());
    
    Run Code Online (Sandbox Code Playgroud)