gpt4 book ai didi

c++ - boost::variant - 为什么 "const char*"转换为 "bool"?

转载 作者:IT老高 更新时间:2023-10-28 22:02:52 27 4
gpt4 key购买 nike

我声明了一个 boost::variant,它接受三种类型:stringboolint。以下代码显示我的变体接受 const char* 并将其转换为 boolboost::variant 接受和转换不在其列表中的类型是正常行为吗?

#include <iostream>
#include "boost/variant/variant.hpp"
#include "boost/variant/apply_visitor.hpp"

using namespace std;
using namespace boost;

typedef variant<string, bool, int> MyVariant;

class TestVariant
: public boost::static_visitor<>
{
public:
void operator()(string &v) const
{
cout << "type: string -> " << v << endl;
}
template<typename U>
void operator()(U &v)const
{
cout << "type: other -> " << v << endl;
}
};

int main(int argc, char **argv)
{
MyVariant s1 = "some string";
apply_visitor(TestVariant(), s1);

MyVariant s2 = string("some string");
apply_visitor(TestVariant(), s2);

return 0;
}

输出:

type: other -> 1
type: string -> some string

如果我从 MyVariant 中删除 bool 类型并将其更改为:

typedef variant<string, int> MyVariant;

const char* 不再转换为 bool。这次它被转换为 string 并且这是新的输出:

type: string -> some string
type: string -> some string

这表明 variant 尝试先将其他类型转换为 bool,然后再转换为 string。如果类型转换是不可避免的并且应该总是发生,有没有办法给 string 的转换提供更高的优先级?

最佳答案

这与 boost::variant 无关,而是与 C++ 选择要应用的转换的顺序有关。在尝试使用用户定义的转换之前(请记住,std::string 是用于此目的的用户定义的类),编译器将尝试内置转换。 const char*int 没有内置转换,但根据标准中的§4.12:

A prvalue of [...] pointer [...] type can be converted to a prvalue of type bool.

因此编译器很乐意将您的 const char* 转换为 bool,并且永远不会考虑将其转换为 std::string

更新:看起来这个明显不需要的转换正在修复。您可以找到修复的技术说明 here .

关于c++ - boost::variant - 为什么 "const char*"转换为 "bool"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13268608/

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