我有以下代碼:C++:使用函數指針作爲模板參數
template<typename Parent, typename T, void (Parent::*Setter)(T), T (Parent::*Getter)()>
struct Property {
Parent& obj;
Property(Parent& _obj) : obj(_obj) {}
Property& operator=(T v) { (obj.*Setter)(v); return *this; }
operator T() { return (obj.*Getter)(); }
};
template<typename T1, typename T2>
class Bimap {
public:
class Entry;
typedef std::tr1::shared_ptr<Entry> EntryP;
typedef std::multimap<T1, EntryP> T1Map;
class Entry {
private:
Bimap& bimap;
typename T1Map::iterator it1;
void set1(T1 v) { bimap.map1.erase(it1); it1 = bimap.map1.insert(typename T1Map::value_type(v, it2->second)).first; }
T1 get1() { return it1->first; }
public:
Property<Entry,T1,set1,get1> first() { return Property<Entry,T1,set1,get1>(*this); }
};
};
此代碼給我(上Property<...> first()
):
'void Bimap<T1, T2>::Entry::set1(T1) [with T1 = double, T2 = std::tr1::shared_ptr<Node>]' cannot appear in a constant-expression
我也試圖與
Property<Entry,T1,&set1,&get1> first() { return Property<Entry,T1,&set1,&get1>(*this); }
但這給了我:
error: wrong number of template arguments (3, should be 4)
error: provided for 'template<class Parent, class T, void (Parent::* Setter)(T), T (Parent::* Getter)()> struct Property'
是否有可能以某種方式解決這一問題?或者爲什麼這是不可能的?
這些都不是普通的函數指針,這些指針到成員函數,所以你必須使用指針到成員的語法。 – 2010-09-19 17:50:14