विषय पर बढ़ें

अंतिम अद्यतन:2026-10-12

एक दिलचस्प C++ code

0. प्रस्तावना

लक्ष्य: lambda या functor के parameters की संख्या कैसे प्राप्त करें?

इस section में template + ::* + decay + decltype से implement करेंगे!

1. Implementation

अंतिम प्रभाव:

auto c1 = [](int x, double y) { return x * y; };
std::cout << argument_count<decltype(c1)>::value << std::endl;
MyClass f;
std::cout << argument_count<decltype(f)>::value << std::endl;

आउटपुट: 2

आइए इस समस्या पर सोचें, इन points को जानना ज़रूरी है:

  • Functor और lambda की position कैसे पकड़ें?
  • इस function signature के parameters की संख्या कैसे प्राप्त करें?

पहले प्रश्न के लिए, हम ::* उपयोग करके member declaration की ओर point कर सकते हैं, functor और lambda दोनों के लिए यह &std::decay<F>::type::operator()) है। सरल शब्दों में, दोनों में operator() declaration का address लिया जाता है।

यहाँ decay से cv qualifiers हटाए जाते हैं, ऊपर वाले MyClass का उदाहरण लें, यहाँ पहले std::decay<F>::type से MyClass type प्राप्त किया जाता है, फिर संगत operator() का address लेकर argument_count_impl को पास किया जाता है।

template <typename F>
using argument_count = decltype(argument_count_impl(&std::decay<F>::type::operator()));

argument_count_impl का implementation भी काफी सरल है, R (F::*)(A...) signature का उपयोग करके संगत function प्राप्त किया जाता है, यहाँ variadic templates, ::* उपयोग हुए हैं, sizeof parameters की संख्या पाने के लिए है, और integral_constant इस compiler constant type को int बताता है, जिसकी value sizeof...(A) है।

template <typename F, typename R, typename... A>
static std::integral_constant<int, sizeof...(A)> argument_count_impl(R (F::*)(A...));

इसके आधार पर, Lambda या Functor के parameters की संख्या पाने की functionality implement हो गई~

संबंधित विषय

टिप्पणियाँ