2

In a project, I came accross following line of code.

::std::unordered_map<std::string, Channel*(*)(Module*, const Parameters&)>;

Does anyone know what Channel*(*) could mean? Is is the same as Channel**? It seems confusing and overcomplicated to me.

The Channel constructor looks like this:

Channel(Module* module, const util::Parameters& parameters);
uro1012
  • 31
  • 3

1 Answers1

5

This:

Channel*(*)(Module*, const Parameters&)

Is pointer to a function that takes a Module* and a const Parameters& as argument and returns a Channel*.

For more details see here: https://en.cppreference.com/w/cpp/language/pointer

Function pointers are look rather intimidating, and an alias makes using them much simpler:

using fun = Channel*(Module*, const Parameters&);
fun* x = &some_function_with_right_signature;
// or
::std::unordered_map<std::string,fptr>;
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
  • 1
    I would recommend avoiding giving aliases to pointers. Non pointer aliases are easier to read, and you don't hide the pointers: `using fun = ret(args); fun* x = &some;` – eerorika Dec 15 '20 at 12:38
  • @eerorika in general thats my rule of thumb, though it never occured to me to apply it for function pointers. Have to think about it ;) – 463035818_is_not_an_ai Dec 15 '20 at 12:40
  • So it is a function pointer to a constructor. From what I understand, it can be used to instantiate an object. Is it destroyed automatically when it is destroyed? If not, how can it be destroyed? – uro1012 Dec 15 '20 at 13:57
  • @uro1012 no, constructors are rather special. It is a pointer to a free function. It could be a `Channel* foo(Module*, const Parameters&);` which calls the constructor and returns a pointer to the constructed object – 463035818_is_not_an_ai Dec 15 '20 at 13:59
  • @uro1012 see here: https://stackoverflow.com/a/954565/4117728 – 463035818_is_not_an_ai Dec 15 '20 at 14:00