Custom arguments in angle brackets and parentheses

// Called with doSomething<5>();
template<unsigned i_>
void doSomething()
{
    std::cout << i_ << '\n';
}

// Called with doSomething(5);
void doSomething(unsigned i_)
{
    std::cout << i_ << '\n';
}

When is the first option preferable? Why is it even available? I understand that this is useful for classes where the arguments in angle brackets are attached to the object itself, and not to the specific constructor, but is it useful for functions?

+4
source share
1 answer

, . template, i_ . , , , . , .

template<unsigned i_>
void doSomething() {
    static int a = 0;
    std::cout << a++ << std::endl;
}

:

doSomething<1>();
doSomething<1>();
doSomething<1>();
doSomething<2>();

:

0
1
2
0

. 2D- .

template<unsigned n>
void doSomething(int (*array)[n]) {
  // ...
}

, , , . :

void doSomething(unsigned i_) {
    static int a = 0;
    std::cout << i_ << " " << a++ << '\n';
}

:

doSomething(1);
doSomething(1);
doSomething(1);
doSomething(2);

:

1 0
1 1
1 2
2 3

:

void doSomething(int (*array)[5]) {
  // ...
}

nx5 ( n - ), . .

: , , , .

+4

Source: https://habr.com/ru/post/1673240/


All Articles