Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ brace initilization with template parameter

Tags:

c++

templates

I'm almost certain this has been answered somewhere, but I can't find it, so I'll just ask.

Compiles fine

template <int SIZE, unsigned int NUMSYNC>
class MyClass{
private:
    std::uniform_int_distribution<int> randomNumberDistribution{ 0, SIZE };
}

Does not compile (constant SIZE is not a type name)

template <int SIZE, unsigned int NUMSYNC>
class MyClass{
private:
    std::uniform_int_distribution<int> randomNumberDistribution( 0, SIZE );
}

I'm trying to understand the difference and why the brace-initialization works, as opposed to the traditional one.

I'm compiling with C++14

like image 449
Norman Pellet Avatar asked Nov 18 '25 09:11

Norman Pellet


1 Answers

This is due to the definition in the standard. Otherwise, it could be impossible for the compiler to distinguish it from a member function declaration when parsing the code.

2) Through a default member initializer, which is a brace or equals initializer included in the member declaration and is used if the member is omitted from the member initializer list of a constructor. (Emphasis by me)

https://en.cppreference.com/w/cpp/language/data_members

like image 164
Jodocus Avatar answered Nov 20 '25 00:11

Jodocus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!