I
I
Insolent Muzzle2021-06-18 06:04:43
C++ / C#
Insolent Muzzle, 2021-06-18 06:04:43

What are the brackets in the std::true_type{} expression?

What is this {} in the expression
bool trueValue = true_type{};

And why does the following code print Hello, World correctly?

#include <iostream>

class hello {
  public:
  operator std::string() {
    return "Hello, World!";
  }
};

int main(int argc, char** argv)
{
  std::string helloWorld = hello{};
  std::cout << helloWorld;
  return 0;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mercury13, 2021-06-18
@pluffie

C++11 universal initializer. It can contain anything: constructor parameters, initializer_list, structure fields... Your code is equivalent to the code

std::string helloWorld(std::move(hello().operator std::string()));

It seems to be true - earlier, NYA, op= COPY CONSTRUCTOR was called in helloWorld , and now C ++ 17 constructor.
For temporary objects, the string(string&&) version is called, I denoted this as string(std::move()).
Well, hello::op string is used to convert hello to string.
hello(), or, since C++11, hello{} is the creation of a temporary object using the default constructor.

R
res2001, 2021-06-18
@res2001

As far as I understand, in your example it is quite possible to replace curly braces with round ones and nothing will change.
But if the hello class had a constructor that takes a std::initializer_list, then if curly braces were used, this constructor would be called, and not the default constructor, even if the curly braces are empty.
Make both constructors and check which one is called with curly braces and with parentheses.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question