Template Return Type with Default Value

前端 未结 6 1535
情歌与酒
情歌与酒 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:29

    The line

    T t;
    

    Default constructs objects, yet declares uninitialized built-in types. There is no syntax to 'default construct' a local variable.

    Therefore it's not trivial to write generic code that initializes a variable, whether built-in or class.

    Wrapping the type into a member variable, however, may present a workaround that does not need copy construction (apart from the return statement):

    template< typename T > struct Initializer {
       T t;
       Initializer()
       :t() // ====> default construction, works for classes _and_ built-in
       {}
    };
    

    Using this wrapper, you can build your code in a generic way:

    template T foo() {
      Initializer i;
      // fill in i.t to your liking
      return i.t;
    }
    

    See a full-blown snippet at codepad.

提交回复
热议问题