سؤال

أريد أن أتبع توسيع الماكرو - كم مرة تم توسيع الماكرو وما هي Args عندما حدث التوسع.

على سبيل المثال،

لدي ماكرو قد يبدو وكأنه هذا: giveacodicetagpre.

وفي التعليمات البرمجية لدي شيء مثل هذا: giveacodicetagpre.

في نهاية التوسع المعالج مسبقا (أوه نعم، هل هناك طريقة لجعل ماكرو معين لتصبح أخيرا للتوسع؟)، أود أن أعرف عدد المرات التي تم استخدام mymacro وما هي Args مرتوبعدفي هذه الحالة، سيكون 2 مرات، وستكون Args A و B.

كنت التحقق في زيادة Bost-Preprocessor Lib.لديهم boost_pp_array، لكنني لا أعرف كيفية جعله "ثابت"، حتى أتمكن من استخدامه في وقت لاحق.

وجدت شيئا في boost_pp_counter.يبدو أن BOOST_PP_COUNER هو شيء يمكنه الحفاظ على حالته في عبارة Preprocessor.ولكن ما زلت غير واضح كيف أفعل ما أردت.

هل كانت مفيدة؟

المحلول

How about something like this?

#include <iostream>

int m_counter = 0;
const char *m_arguments[32] = { 0 };

#define COUNT_M(a) m_arguments[m_counter++] = #a;
#define M(a) COUNT_M(a) int a

int main()
{
    M(x);
    M(y);

    for (int i = 0; i < m_counter; i++)
    {
        std::cout << "m_arguments[" << i << "] = \"" << m_arguments[i] << "\"\n";
    }
}

نصائح أخرى

I'm not quite sure what your ultimate goal is, but you can track the number of scans(not the number of expansions) using an active argument. An active argument expands each time that it is scanned by the preprocessor. For example,

#define EMPTY()

#define A(n) \
    A_INDIRECT EMPTY()()(BOOST_PP_INC(n)) 

#define A_INDIRECT() A

#define X(arg) arg
#define Y(arg) X(arg)
#define Z(arg) Y(arg)

   A(0)   // A_INDIRECT()(1)
X( A(0) ) // A_INDIRECT()(2)
Y( A(0) ) // A_INDIRECT()(3)
Z( A(0) ) // A_INDIRECT()(4)

Each invocation of A is subjected to a different number of scans, which causes the results to be different each time.

Macros can't effect the global state. The only other way to achieve some sort of state is to use recursion. Remember, macros don't expand recursively, so the preprocessor keeps tracks of this state. Its the only "global" state that can be affected by macros. However, it can be difficult to control. Macros have to be forced to expand at a certain recursion level with a macro for each level, and some form of binary searching is required to read the "state" efficiently.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top