2014-01-11 28 views
0

以下TestClass作品:成員函數模板使用boost ::功能

#include <iostream> 
#include <boost/function.hpp> 
#include <boost/bind.hpp> 

void ext_fun(const float f, int i) 
{ 
    std::cout << f << '\t' << i << std::endl; 
} 

template <typename T> 
class TestClass 
{ 
public: 
    boost::function <void (const T)> test_fun; 
}; 

int main() 
{ 
    TestClass<float> tt; 
    tt.test_fun = std::bind(ext_fun, std::placeholders::_1, 10); 
    tt.test_fun(2.1); 
    return(0); 
} 

不過,我更願意定義test_fun作爲一個成員函數模板,即像

class TestClass 
{ 
public: 
    template <typename T> boost::function <void (const T)> test_fun; 
}; 

但如果我這樣做,我得到這個編譯器錯誤:「錯誤:數據成員'test_fun'不能成爲成員模板」

是否可以定義一個成員函數離子模板使用boost::function?如果是,如何?

謝謝

--Matteo

+0

對不起,這沒有意義 - 這不是「功能模板」的意思。你問的問題相當於「我可以把'struct Foo {int a;};'轉換爲'struct Foo {template T a;};'」,你不能。 –

+0

@Kerrek SB我指的是像第一個例子[這裏](http://msdn.microsoft.com/en-us/library/swta9c6e%28VS.80%29.aspx),或者問題[here ](http://stackoverflow.com/questions/972152/how-to-create-a-template-function-within-a-class-c),但使用'boost :: function' –

回答

0

Is it possible to define a member function template using a boost::function ? If yes, how?

我想你混淆會在這裏一點點。功能模板首先是功能。您的test_fun不是函數,它是類TestClass的成員對象。成員對象不能用C++模板化。

+0

好吧,所以點是:類方法可以模板化(像[這裏](http://msdn.microsoft.com/en-us/library/swta9c6e%28VS.80%29.aspx)),但如果我使用'boost :: function '我實際上並沒有一個方法,而是一個成員**對象**。所以它不能被模板化。它是否正確? –

+0

@MatteoM。,C++中不存在「類方法」的術語:您應該習慣使用「成員函數」。但是,這個概念是正確的。 'boost :: function'是一個類類型,它引導聲明'boost :: function test_fun;'成爲一個無法模板化的對象。 – Shoe