簡體   English   中英

如何在C ++中訪問指針傳遞函數的參數

[英]How to access a parameter of a passed-as-pointer function in c++

我有一個母函數,它接受一個函數作為其指針。 傳遞的函數接受整數X。在母函數內部,我喜歡訪問整數X。應如何做? 以下引發未定義的錯誤:

bool assign_threads_instructions(void* (* _instr)(int socket_fd) )
{

    int pool_size = get_threads_pool_size();
    for(int i = 0; i < pool_size; i++)
    {
        threads_pool[i] = std::thread(_instr, socket_fd); // here I access the socket_fd parameter throws undefined error
    }
}

_instr是具有int參數的函數的(可能)地址,因為void* (* _instr)(int socket_fd)聲明了一個名為_instr的指針,該指針可以指向返回void*的函數,並接受一個名為socket_fd int參數。 因此,沒有socket_fd變量,因為您不能(至少不像通過函數指針那樣簡單)傳遞帶有參數的可調用對象。

您可以分別傳遞該值:

bool assign_threads_instructions(void* (* _instr)(int), int _fd)
{
    std::size_t pool_size = get_threads_pool_size();
    for(std::size_t i = 0; i < pool_size; ++i)
    {
        threads_pool[i] = std::thread(_instr, _fd);
    }
}

或具有一個assign_threads_instructions待推論參數的模板assign_threads_instructions函數,並使用std::bind生成具有所需值的可調用包裝。

std::bind示例:

如果您有一個分配功能模板,例如:

template<class F>
void assign_stuff(F&& _f)
{
  std::thread work(_f);
  work.join();
}

您可以使用它通過std :: bind將回調和值打包到一個參數中:

void f(int& x)
{
  x = x + 2;
}
int main() 
{
  int q = 55;
  assign_stuff(std::bind(&f, std::ref(q)));
  std::cout << q << "\n";
  return 0;
}

版畫

57

函數指針只是函數指針

函數assign_threads_instructions的聲明采用一個參數: _instr的類型為void* (*_instr) (int)

函數的指針接受一個int並返回指向void指針。

類型內int的不必要命名除了可讀性外沒有其他作用。

使用現代C ++語法可以使這一點更加清楚。

using callback_t = std::add_pointer_t<void*(int)>;
bool assign_threads_instructions(callback_t instr) { /* ... */ }

顯而易見的答案是,您必須將值和回調一起傳遞給函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM