我不確定以下是否可能。有人可以提供這個要求的等效物嗎?是否可以將函數名稱等同於另一個函數名稱?
if(dimension==2)
function = function2D();
else if(dimension==3)
function = function3D();
for(....) {
function();
}
我不確定以下是否可能。有人可以提供這個要求的等效物嗎?是否可以將函數名稱等同於另一個函數名稱?
if(dimension==2)
function = function2D();
else if(dimension==3)
function = function3D();
for(....) {
function();
}
這是可能的,假定兩件事情:
function2D()
和function3D()
具有相同簽名和返回類型。function
是一個函數指針,具有相同的返回類型和參數都function2D
和function3D
。您正在探索的技術與構建jump table時使用的技術非常相似。您有一個函數指針,您可以根據運行時條件在運行時分配(並調用)。
下面是一個例子:
int function2D()
{
// ...
}
int function3D()
{
// ...
}
int main()
{
int (*function)(); // Declaration of a pointer named 'function', which is a function pointer. The pointer points to a function returning an 'int' and takes no parameters.
// ...
if(dimension==2)
function = function2D; // note no parens here. We want the address of the function -- not to call the function
else if(dimension==3)
function = function3D;
for (...)
{
function();
}
}
大的upvote將此與跳轉表相關聯。精彩的解釋。 – 2013-10-24 18:04:54
@ H2CO3:謝謝。 :)太糟糕了,我被封頂了。 –
您可以使用函數指針。
有一個tutorial here但基本上你要做的就是聲明它是這樣的:
void (*foo)(int);
其中函數有一個整型參數。
然後調用它像這樣:
void my_int_func(int x)
{
printf("%d\n", x);
}
int main()
{
void (*foo)(int);
foo = &my_int_func;
/* call my_int_func (note that you do not need to write (*foo)(2)) */
foo(2);
/* but if you want to, you may */
(*foo)(2);
return 0;
}
所以只要你的函數具有相同數量和參數的類型,你應該能夠做你想做的。
因爲這也標記了C++,你可以使用std::function
,如果你要C++11
,或std::tr1::function
訪問,如果你的編譯器支持C++ 98/03和TR1。
int function2d();
int function3D();
int main() {
std::function<int (void)> f; // replace this with the signature you require.
if (dimension == 2)
f = function2D;
else if (dimension == 3)
f = function3D;
int result = f(); // Call the function.
}
正如在其他答案中提到的,確保你的函數具有相同的簽名,一切都會好。
如果您的編譯器不提供std::function
或std::tr1::function
,總是有boost library。
既然你選擇C++
與std::function
例如下面是C++ 11
#include <functional>
#include <iostream>
int function2D(void)
{
// ...
}
int function3D(void)
{
// ...
}
int main()
{
std::function<int(void)> fun = function2D;
fun();
}
是的,'std :: function'在C++中可能是正確的。 – 2013-10-24 18:11:08
C或C++?你需要的是一個函數指針 – P0W
「我知道以下是不可能的。」 - 它是。 – 2013-10-24 18:00:08
@ H2CO3:冷卻。我不知道!感謝您通知... :) –