2010-09-01 100 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