V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
htfy96
V2EX  ›  问与答

C++ boost::variant 重载<<的问题?

  •  
  •   htfy96 · 2015-07-31 11:59:02 +08:00 · 1576 次点击
    这是一个创建于 3207 天前的主题,其中的信息可能已经有所发展或是发生改变。

    现在使用boost::variant<bool, int, std::string>来存储token的内容。

    boost::variant会自动根据里面的类型匹配正确的<<,std::cout<<token<<std::endl;是可行的

    然而在输出时,我们希望改变输出时的表现。

    改变输出时的表现有两种方法:

    • 改变流本身,自定义新流的<<操作符。考虑到这样对整体侵入过大,遂放弃。

    • 给它们创建一个Formatter:(这是stackoverflow上的一个答案)

    template <class T>
    class MyFormatting;
    
    template <>
    class MyFormatting<int>
    {
    private:
        const int& nucleus;
    
    public:
        MyFormatting(const int& n) : nucleus(n) {}
    
        friend std::ostream& operator << (std::ostream& os, const MyFormatting& w)
        {
            return os << "int:" << w.nucleus;
        }
    };
    //... specilization for bool and std::string
    
    template <class... T>
    using Variant_Formatting_t = boost::variant < MyFormatting<T>... > ;
    
    Variant_Formatting_t<bool, int, std::string> 
    FMT(const boost::variant<bool, int, std::string>& A__)
    {
     return Variant_Formatting_t<bool, int, std::string>{A__}; 
    }
    
    int main()
    {
        boost::variant<bool, int, std::string> var_int = 3;
        boost::variant<bool, int, std::string> var_str = "12312312";
        std::cout << FMT(var_int)<< FMT(var_str) <<  std::endl;
    }
    

    这种方法在只有int & string时是有效的,因为:
    Variant_Formatting_t<bool, int, std::string>{3};
    中,
    Variant_Formatting_t作为variant< MyFormatter<bool>, MyFormatter<int>, ... >
    会尝试调用initilize(void, 3)

    而其原型有
    initilize(void
    , const MyFormatter<string>&)

    initilize(void*, const MyFormatter<int>&)
    只有(2)可以匹配,完成转换

    然而,当我们加上bool时,由于
    initilize(void, 3)

    有了3个原型:
    initilize(void
    , const MyFormatter<string>&)
    initilize(void, const MyFormatter<int>&)
    initilize(void
    , const MyFormatter<bool>&)
    其中2 3的优先级是等价的(都是template class conversion),从而导致这段代码失败

    请问有什么好的解决办法吗?

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   5090 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 09:44 · PVG 17:44 · LAX 02:44 · JFK 05:44
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.