2013-10-21 46 views
0

我有一個C接口的C++包裝類。在該界面中的一個函數都有一個默認的參數一個參數:使用包裝函數指針來處理參數的默認值

api.h: 
int Foo(int bar=5); 

這是包裝:

Wrapper.hpp: 
class Wrapper 
{ 
public: 
    static int (*Foo) (int bar); 
} 

Wrapper.cpp: 
int (*Wrapper::Foo)(int bar); 

這是我使用的功能與包裝:

Wrapper::Foo(5); 

但我也希望能夠在沒有參數的情況下致電Foo,因此它需要默認值5

Wrapper::Foo(); 

我該怎麼做?

回答

3

由於缺省參數被禁止用於函數指針,因此無法將函數int(int)指定給函數int(),因此只能使用函數指針。

N3376 8.3.6/3

默認參數,應僅在函數聲明

爲什麼要使用指針參數聲明子句指定?只需編寫函數,即可從API調用函數。

class Wrapper 
{ 
public: 
    static int Foo (int bar) 
    { 
     return ::Foo(bar); 
    } 
    static int Foo() 
    { 
     return ::Foo(); 
    } 
} 

Wrapper::Foo(1); 
Wrapper::Foo(); 
+1

但是請注意,您不能保證包裝中使用的默認值與API中的默認值相同,尤其是如果您無法控制API並且默認值可能隨時更改。 – arne

+0

@arne同意。現在沒有這樣的問題。 – ForEveR