【问题标题】:C++ function converting questionC++函数转换问题
【发布时间】:2010-11-14 23:05:44
【问题描述】:

我尝试使用boost::function<x> 包装器来存储和转换我的功能对象,我想知道是否存在“从任意类型T 到类型boost::function<x> 的转换是否存在”的编译检查

这是一个代码示例:

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 类型特征检查,但它会为任何Functor 类型生成true

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;

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

谢谢。

【问题讨论】:

    标签: c++ templates boost metaprogramming type-conversion


    【解决方案1】:

    除了@James 写的内容之外,您似乎更希望拥有类似is_callable 的内容。 These class templates 处理函数/函数指针和函数对象类或对最多 5 个参数的引用。使用它们需要您自担风险:)

    【讨论】:

    • 谁-呼-呼,谢谢。这是我正在寻找的改编版本。
    【解决方案2】:
    当您测试 any 类型是否可转换为 any boost::function 类型时,

    boost::is_convertible 产生 true,因为 boost::function 有一个转换构造函数模板,该模板采用 任何类型。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-17
      • 2016-11-27
      • 1970-01-01
      • 1970-01-01
      • 2014-12-02
      相关资源
      最近更新 更多