2017-04-06 230 views
2

這裏的東西,它似乎很可能通過一個模板化的結構裏面包含一些靜態函數是這樣的:如何將模板函數作爲模板類參數傳遞?

template <class T> struct FunctionHolder {}; 

template <> struct FunctionHolder<string> { 
    static void f(const string &s) { 
     cout << "f call " << s << endl; 
    } 
}; 

template <class Key, class Value, class Holder = FunctionHolder<Key>> 
class Foo { 
    public: 
    Foo(Key k) { 
     Holder::f(k); 
    } 
}; 

int main(int argc, char *argv[]) { 
    Foo<string, int> foo = Foo<string, int>("test_string"); 
} 

但是,纔有可能通過直接模板化的功能,而不會被靜態定義的模板化的結構?我已經試過這一點,它不會編譯:

template <class string> static void f(const string &s) { 
    cout << "f call " << k << endl; 
} 

template <class Key, class Value, typename func<Key>> class Foo { 
    public: 
    Foo(Key k) { 
     func(k); 
    } 
}; 

int main(int argc, char *argv[]) { 
    Foo<string, int> foo = Foo<string, int>("test_string"); 
} 

問這個因爲這一切的不冷靜而被迫創建虛擬結構(含一堆靜態功能結構)用作模板類型爲主類。

+0

爲什麼不'FUNC ''在構造函數Foo'?提供用例。 – Yakk

回答

1

不幸的是,功能模板不能用作template template arguments;您可以使用函數指針作爲非類型模板參數,例如

template <class Key, class Value, void(*func)(const Key&) = f<Key>> class Foo { 
    public: 
    Foo(Key k) { 
     func(k); 
    } 
}; 

LIVE

+0

@BPL對不起,我無法訪問你張貼的網址(我的網絡不好);我嘗試了一個演示[在這裏](http://rextester.com/EYJTKA4322)。 – songyuanyao

+0

@BPL只需更改參數名稱;不要使用'int'。 http://rextester.com/FGQB33074 – songyuanyao

相關問題