2010-06-16 181 views
21

我知道这是可能分开来创建这样指针const成员函数的typedef

struct K { void func() {} }; 
typedef void FuncType(); 
typedef FuncType K::* MemFuncType; 
MemFuncType pF = &K::func; 

一个成员函数指针有没有类似的方式来构建一个指向一个const函数?我试过在各个地方添加const没有成功。我打得周围用gcc一些,如果你做模板扣除,像

template <typename Sig, typename Klass> 
void deduce(Sig Klass::*); 

它会显示西格以与常量函数签名只是上涨了尽头。如果在代码中这样做,它会抱怨你不能在函数类型上使用限定符。似乎应该有可能以某种方式,因为扣除的作品。

回答

32

你想这样的:

typedef void (K::*MemFuncType)() const; 

如果你想在FuncType仍然立足MemFuncType,您需要更改FuncType

typedef void FuncType() const; 
typedef FuncType K::* MemFuncType; 
+0

是的,你是对的它的作品!我以为我尝试了第二个,但不要猜测,那是另一台机器,虽然也许是旧的编译器。将不得不明天再次检查。 – oldcig 2010-06-16 05:09:37

6

展示了如何做没有一个typedef轻微细化。 在如下所示的推演环境中,不能使用typedef。

template <typename Class, typename Field> 
Field extract_field(const Class& obj, Field (Class::*getter)() const) 
{ 
    return (obj.*getter)(); 
} 

应用于一些类与常量消气:

class Foo { 
public: 
    int get_int() const; 
}; 

Foo obj; 
int sz = extract_field(obj, &Foo::get_int);