Mam problem ze zrozumieniem typy funkcyjne (pojawiają się one na przykład jako parametr Signature
szablonu z std::function
):C++ typy funkcyjne
typedef int Signature(int); // the signature in question
typedef std::function<int(int)> std_fun_1;
typedef std::function<Signature> std_fun_2;
static_assert(std::is_same<std_fun_1, std_fun_2>::value,
"They are the same, cool.");
int square(int x) { return x*x; }
Signature* pf = square; // pf is a function pointer, easy
Signature f; // but what the hell is this?
f(42); // this compiles but doesn't link
Zmienna f
nie można przypisać, ale można nazwać. Dziwne. Po co więc jest to dobre?
Teraz gdybym const zakwalifikować typedef, mogę nadal używać go do budowania kolejnych rodzajów ale widocznie do niczego innego:
typedef int ConstSig(int) const;
typedef std::function<int(int) const> std_fun_3;
typedef std::function<ConstSig> std_fun_4;
static_assert(std::is_same<std_fun_3, std_fun_4>::value,
"Also the same, ok.");
ConstSig* pfc = square; // "Pointer to function type cannot have const qualifier"
ConstSig fc; // "Non-member function cannot have const qualifier"
Co odległy zakątek języku ja tu trafić? W jaki sposób wywoływany jest ten dziwny typ i jak mogę go użyć poza parametrami szablonu?
Standardowo po prostu pozwala zadeklarować * * funkcje przez typedef do ich podpisania (faktycznie, typu funkcja). – Xeo