2

Suppose I have a function template and want to declare a value-initialized object:

template<typename T>
void foo() {
    // declare and default-initialize 'x' of type 'T'
}

Can I do it?

  • T x; fails for primitive types because it leaves them uninitialized,
  • T x(); fails because of the most vexing parse
  • T x = T(); requires a copy constructor and doesn't require the compiler elide the copy
  • T x{}; fails because we're not using C++11.

I'm hoping I'm being an idiot and overlooking something obvious, but I'm not seeing the answer.

EvanED
  • 947
  • 6
  • 22

1 Answers1

1

Pre c++11

T x = T();

read here - link

T3 var3 = {};

The third form, T3 var3 = {} initializes an aggregate, typically a "C-style" struct or a "C-style" array. However, the syntax is not allowed for a class that has an explicitly declared constructor.

source

Community
  • 1
  • 1
Tarik Neaj
  • 548
  • 2
  • 10
  • 2
    The OP knows that but `T` needs to by copyable for this to work. – NathanOliver Jan 08 '16 at 18:34
  • That's the best answer that I know of, but it's not perfect. I'm asking if there's a better one. That said, the fact that there weren't better answers at your link indicates there probably isn't a better one, so I do thank you for it. (I did some searching but didn't find that.) – EvanED Jan 08 '16 at 18:34
  • Not sure if the one I just found is of any help, I edited my post. – Tarik Neaj Jan 08 '16 at 18:37