Template Return Type with Default Value

前端 未结 6 1532
情歌与酒
情歌与酒 2021-02-10 20:46

So in writing a C++ template class, I have defined a method that returns an object of the templated type, as such:

template 
class Foo
{
public         


        
6条回答
  •  暖寄归人
    2021-02-10 21:30

    This seems to work for primitive types (such as int and float) and classes, at least so long as that class has a copy constructor

    For classes, not only [public] copy-constructor, you also need public default constructor!

    My question is - is this the accepted way of solving this problem?

    Usually it's a good idea to provide public default constructor. STL containers use it all the time! If you don't have one, most (or maybe, all) STL containers would not work at many occasions.

    See this example with private default constructor: http://ideone.com/EdPLu

提交回复
热议问题