没有可行的从std::函数到bool的转换
No viable conversion from std::function to bool
c++ 11 std::function
应该实现operator bool() const
,那么为什么clang告诉我没有可行的转换?
#include <functional>
#include <cstdio>
inline double the_answer()
{ return 42.0; }
int main()
{
std::function<double()> f;
bool yes = (f = the_answer);
if (yes) printf("The answer is %.2fn",f());
}
编译错误是:
function_bool.cpp:12:7: error: no viable conversion from 'std::function<double ()>' to 'bool'
bool yes = (f = the_answer);
^ ~~~~~~~~~~~~~~~~
1 error generated.
EDIT我没有看到explicit
关键字。没有隐式转换那么,我想我将不得不使用static_cast
。
operator bool()
对于std::function
是explicit
,因此它不能用于复制初始化。你可以直接初始化:
bool yes(f = the_answer);
然而,我认为它实际上是用于上下文转换,当表达式用作条件时,通常用于if
语句。上下文转换可以调用explicit
构造函数和转换函数,这与隐式转换不同。
// this is fine (although compiler might warn)
if (f = the_answer) {
// ...
}
相关文章:
- 使用 bool 和 const char 重载的 C++ 函数会在没有警告的情况下产生歧义 (MSVC2012)
- 合并 2 个排序的链表。必需的成员函数 bool Merge(List342 &list1):
- C bool表达式作为函数参数调用错误的超载
- 将 std::vector<bool> 传递给外部函数
- 尝试创建一个评估字符的bool函数,如果字母数字为字母,则返回true
- 引用 std::atomic <bool>的已删除函数错误
- bool值不在腔函数函数中重新调整false,c
- 在矩阵C 中使用Bool函数检查重复数字
- 当Bool值在UPDATE()方法中更改时,只有一次呼叫函数
- 我的bool函数一直返回true,我不知道为什么
- 返回 std::p air<const CustomClass &, bool> 用于搜索函数中的失败情况,当 CustomClass 是抽象基类时
- C++变体用bool转换构造函数
- 使用 Bool 函数在 C++ 中进行递归二叉搜索
- 为什么带有Bool参数的函数接受String
- 如何存储CUDA内核函数的Bool结果
- 为什么函数向bool存在隐式转换
- 用bool函数确定末端
- 带有 bool 参数的构造函数总是用 _T( "..." )调用?
- c++中函数bool isnan(…)的定点实现
- 如何为 std::vector<std::vector 编写哈希函数<bool>>