c++ - boost::variant 隐式转换为字符串

标签 c++ implicit-conversion boost-variant

我有一个具有不同类型的 boost::variant,其中一个是(const)void 指针,另一个是字符串。

boost::variant<std::string, void const*>;

问题是,如果我想将它与 c 字符串一起使用,它会将其转换为 void 指针而不是字符串。

boost::variant<std::string, void const*> foo;
foo = "bar";
std::cout << foo.which(); // prints 1 -> void const*

如果我删除指针的常量,它会将其转换为字符串。

boost::variant<std::string, void*> foo; // no const pointer
foo = "bar";
std::cout << foo.which(); // prints 0 -> string

是否有一种简单的方法可以使 boost::variant 隐式地​​将 c 字符串转换为 std::string?

更新

我知道我可以使用显式转换:

foo = std::string("bar");

但我想避免显式转换。

最佳答案

您可以通过继承 boost::variant 来提供自己的变体模板。 从 const char*std::string 的正确转换是通过重载 operator= 实现的:

#include <iostream>
#include <string>
#include <boost/variant.hpp>

template <typename... Types>
struct my_variant : public boost::variant<Types...>
{
    using boost::variant<Types...>::variant;

    auto operator=(const char* rhs)
    {
        return boost::variant<Types...>::operator=(std::string(rhs));
    }
};

int main() 
{
    my_variant<std::string, void const*> foo;
    foo = "bar";
    std::cout << foo.which(); 
    return 0;
}

根据需要输出“0”。

实例:https://ideone.com/ZppUla

通过使用指定类型映射的特征类,这个想法可以更加普遍:

template <template <typename> class conv_traits, typename... Types>
struct my_variant : public boost::variant<Types...>
{
    using boost::variant<Types...>::variant;

    template <typename T>
    auto operator=(T rhs)
    {
        return boost::variant<Types...>::operator=(static_cast<typename conv_traits<T>::type>(rhs));
    }
};

template <typename T>
struct conversion_traits
{
    typedef T type;
};

template <>
struct conversion_traits<const char*>
{
    typedef std::string type;
};

my_variant<conversion_traits, std::string, void const*> foo;

实例:https://ideone.com/AXUqTv

关于c++ - boost::variant 隐式转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31008568/

相关文章:

c++ - 虚拟继承在不需要或不使用时是否有成本?

c# - C#如何制作行为类似于Nullable <T>的类

c++ - boost::variant 构造怪异 - 它的 ctor 接受一切

c++ - 用于删除一系列值的 STL 容器

C++ 没有构造函数的实例与参数列表匹配。

c# - C#中的隐式转换而不创建新对象

c++ - 如何增加 boost::variant 可以处理的类型数量

c++ - 从变量 <C,B> 分配变量 <A,B,C>?

c++ - 使用 GLFW 一次处理多个键输入

Scala:带类型参数的类的隐式证据