How to correctly initialize member variable of template type?

前端 未结 2 2018
孤独总比滥情好
孤独总比滥情好 2020-11-29 05:11

suggest i have a template function like following:

template
void doSomething()
{
    T a; // a is correctly initialized if T is a class with a         


        
相关标签:
2条回答
  • 2020-11-29 05:50

    Like so:

    T a{};
    

    Pre-C++11, this was the simplest approximation:

    T a = T();
    

    But it requires T be copyable (though the copy is certainly going to be elided).

    0 讨论(0)
  • 2020-11-29 05:58

    Class template field in C++11 has the same syntax:

    template <class T>
    class A {
      public:
        A() {}
        A(T v) : val(v) {}
      private:
        T val{};
    };
    
    0 讨论(0)
提交回复
热议问题