2013-06-03 50 views
1

编写接受谓词函数的函数(如下面的函数)时;如何确保谓词函数有效(即返回类型operator()有效)?确保谓词函数在C++模板化函数中有效

template <typename Predicate> 
std::vector<SomeType> SearchList(Predicate func) 
{ 
    std::vector<SomeType> vecResults; 
    for(const auto& someObj : someTypeList) 
    { 
      if(func(someObj)) 
       vecResults.emplace_back(someObj); 
    } 

    return vecResults; 
} 

在C++ 11的类型,特点设施环顾四周,我发现std::is_convertible<From,To>,它看起来像它应该帮助,虽然我不知道如何使用它来检查有合适的从operator()bool的隐式转换。我能想到的唯一的事情是:

static_assert(std::is_convertible<Predicate(SomeType), bool>::value, "Predicate type must be convertible to bool"); 

或者:

static_assert(std::is_convertible<Predicate::operator()(SomeType), bool>::value, "Predicate type must be convertible to bool"); 

但没有这些似乎看起来是正确的我。

+0

我不知道你的问题...如果'func(someObj)'的返回类型不能转换为'bool',那么代码'if(func(someObj))'不会被编译......或者你想强制返回类型是_exactly_ 'bool'?或者给自定义的错误信息? –

+0

@ gx_:可能是这样,但'static_assert'会生成更好的错误消息。 –

回答

1

你可以使用:

#include <utility> // For std::declval<>() 

static_assert(
    std::is_convertible<decltype(func(std::declval<SomeType>())), bool>::value, 
    "Predicate's return type must be convertible to bool"); 

如果你只有类型Predicate或不想在表达式中使用func

static_assert(
    std::is_convertible< 
     decltype(std::declval<Predicate&>()(std::declval<SomeType>())), 
     bool>::value, 
    "Predicate's return type must be convertible to bool");