2010-11-14 50 views
3

我试图使用boost::function<x>包装储存和转换我的功能对象,我想知道是否有一个编译支票“从任意类型T做了转换输入boost::function<x>存在”C++函数转换问题

这里是一个代码示例:

struct Functor { 
    int operator()(int) { 
     return 5; 
    } 
}; 

// Should not fire static assertion. 
STATIC_ASSERT((IS_CONVERTIBLE<Functor, 
           boost::function<int (int)> >::value)); 

// Should fire static assertion. 
STATIC_ASSERT((IS_CONVERTIBLE<Functor, 
           boost::function<int (std::string)> >::value)); 

现在 - 没有一种方法来实现IS_CONVERTIBLE检查是否存在?


我试图利用boost::is_convertible型性状检查,但它产生true任何Functor类型:

bool value1 = boost::is_convertible<Functor, 
            boost::function<int (int)> >::value; 

bool value2 = boost::is_convertible<Functor, 
            boost::function<int (std::string)> >::value; 

// At this point both 'value1' and 'value2' equal TRUE. 

我也有以下尝试:

// Here the results are also always TRUE. 
bool value = boost::is_convertible<Functor, 
            boost::function1<int, int> >::value; 

// This doesn't work, because unary functions are constructed via 
// inheritance (the result is always FALSE). 
bool value = boost::is_convertible<Functor, 
            std::unary_function<int, int>::value; 

我真的希望能够在编译时检查这种转换的可能性,所以 如果有人知道如何实现这一点,我将不胜感激。

谢谢。

回答

1

除了@James写的东西,你似乎还想拥有类似is_callable的东西。 These class templates处理函数/函数指针和函数对象类或对它们的引用最多5个参数。使用它们需要您自担风险:)

+0

Who-hoo-hoo,谢谢。这是我正在寻找的适应版本。 – 2010-11-15 00:44:00

1

boost::is_convertible当你测试任何类型是否可转换为产生真正的任何boost::function类型,因为boost::function有一个转换构造函数模板采用任何类型。

因为这个转换构造函数存在,我不知道有一种简单的方法可以测试一个类型是否为实际上可转换为std::function