2010-09-01 48 views
2

我想基本上在這裏做3件事:使用模板重載賦值運算符,限制類型(使用boost :: enable_if),並具有特定的返回類型。enable_if在重載操作符與不同的返回類型

拿這個作爲一個例子:

template <class T> 
std::string operator =(T t) { return "some string"; } 

現在,根據提振enable_if(秒3,子彈,第1部分),我將不得不使用enable_if返回類型,因爲我超載運營這隻能採取一個參數。但是,我希望返回類型爲b字符串,因此它可能不一定與模板參數的類型相同。

我想使用enable_if只是因爲我想它只是跳過模板,如果它不是一個有效的類型(不拋出一個錯誤)。

任何人都有如何完成這個想法?

+0

將您實際需要的類型(在本例中爲std :: string)傳遞給enable_if。 – 2010-09-02 12:40:46

回答

3
#include <iostream> 
#include <boost/utility/enable_if.hpp> 
#include <boost/mpl/vector.hpp> 
#include <boost/mpl/contains.hpp> 

class FooBar 
{ 
public: 
    FooBar() {} 
    ~FooBar() {} 

    template <typename T> 
    typename boost::enable_if < 
     typename boost::mpl::contains < 
      boost::mpl::vector<std::string, int>, T>::type, 
      std::string>::type 
    operator = (T v) 
    { 
     return "some string"; 
    } 
}; 

int 
main() 
{ 
    FooBar bar; 
    bar = 1; 
    bar = std::string ("foo"); 
    // bar = "bar"; // This will give a compilation error because we have enabled 
        // our operator only for std::string and int types. 
} 
+0

很棒,這是增強庫功能強大的一個很好的例子。謝謝。 – elmt 2010-09-02 13:16:56