gpt4 book ai didi

c++ - boost::get boost::variant 没有给出正确的输出

转载 作者:行者123 更新时间:2023-11-30 01:58:15 25 4
gpt4 key购买 nike

我有以下功能

template <typename T, typename U>
const T* visitor_fct(U& operand)
{
return (boost::get<T>(&operand));
}

当我这样做

 boost::variant<int, std::string> str = "string";
std::cout << visitor_fct<std::string>(str) << std::endl;

我得到了正确的输出

但是当我将 str 的声明更改为:

boost::variant<int, std::string, bool> str = "toto";

我总是收到 nullptr ;

为什么?

最佳答案

原因是字符串文字 (char*) 转换为 bool 比转换为 std::string 更好,因此您的字符串文字不会'初始化变体的 string 组件,而不是 bool 组件(为 true)。

查看以下输出 bool 1:

#include <iostream>

void foo(bool b)
{
std::cout << "bool " << b << std::endl;
}

void foo(std::string s)
{
std::cout << "string " << s << std::endl;
}

int main()
{
foo("Bar");
}

使用 std::string("toto") 初始化将解决您的问题。

4.12/1 向我们展示了有问题的转换:

A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a
prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false;
any other value is converted to true. A prvalue of type std::nullptr_t can be converted to a prvalue of
type bool; the resulting value is false.

[如另一个答案中所述]此隐式转换优先于 std::string 的转换构造函数,因此被选中,导致变体中使用的类型为 bool

关于c++ - boost::get boost::variant 没有给出正确的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17662954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com