Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ 11 Curly Braces

Tags:

I haven't used C++ for a good few years, and have just come across this:

program.build({ default_device }) 

The definition is:

cl_int build(     const VECTOR_CLASS<Device>& devices,     const char* options = NULL,     void (CL_CALLBACK * notifyFptr)(cl_program, void *) = NULL,     void* data = NULL) const 

What are the curly braces there for? I have never seen them used in a function call like this before. I assume it has something to do with the function pointer, but that seems optional?

like image 657
rhughes Avatar asked Jan 25 '14 15:01

rhughes


People also ask

Why do braces have curly C?

Different programming languages have various ways to delineate the start and end points of a programming structure, such as a loop, method or conditional statement. For example, Java and C++ are often referred to as curly brace languages because curly braces are used to define the start and end of a code block.

Can we skip the curly braces?

So we can omit curly braces only there is a single statement under if-else or loop. Here in both of the cases, the Line1 is in the if block but Line2 is not in the if block. So if the condition fails, or it satisfies the Line2 will be executed always.

What do curly braces mean?

curly bracket in British English Brackets (also called parentheses) are used to enclose a word or words which can be left out and still leave a meaningful sentence.

Should curly braces appear on their own line?

We strongly recommend you format your curly brackets following Java conventions: Do not put a new line before an opening curly bracket. Always start a new line after an opening curly bracket. A closing curly bracket should always belong on a separate line, except for else statements.


2 Answers

std::vector has a constructor that takes an std::initializer_list.

An initializer_list can be expressed with curly braces.

So this code creates a vector with one default_device in it and passes it to the build member function.

like image 60
typ1232 Avatar answered Oct 25 '22 21:10

typ1232


In:

program.build({ default_device }) 

you are automagically instantiating a temporary VECTOR_CLASS<Device> object. It is equivalent to:

program.build(VECTOR_CLASS<Device>{ default_device }) 

which is equivalent to:

program.build(std::vector<Device>{ default_device }) 

which will call the std::initializer_list constructor:

std::vector::vector(std::initializer_list<T> init,      const Allocator& alloc = Allocator()); 
like image 45
Shoe Avatar answered Oct 25 '22 21:10

Shoe