代码之家  ›  专栏  ›  技术社区  ›  Peter VARGA

静态断言失败:变量不能有引用替代项

  •  2
  • Peter VARGA  · 技术社区  · 7 年前

    我想要一个包含对不同类型变量的引用的映射。为了这个我在用 std::variant 这样地:

    using foo = std::variant<std::atomic<double> &, std::atomic<int> &, std::string &>;
    

    这是gcc 7.3.0的编译版本。使用的编译器标志: -Wall -Wextra -Werror -O3 -std=c++17

    添加此代码:

    using ServerParameter = struct ServerParameter
    {
        foo  myVariants;     <---- gcc error
        bool someLogic;
    };
    

    中断代码,我得到这个gcc错误:

    错误:静态断言失败:变量不能有引用 可供替代的

    我的意图是这样的-但目前我不能因为 using 对于 ServerParameter 已经失败:

    auto bar() -> void
    {    
        std::atomic<double> atom_double;
        std::atomic<int>    atom_int;
        std::string         myString;
        ...
        std::map<std::string, ServerParameter> variableList(
            {
                { {"SomeText1" }, { atom_double; true  } },
                { {"SomeText2" }, { atom_int;    true  } },
                { {"SomeText3" }, { myString;    false } },
            }
        );
        ...
    }
    

    我可以很好地处理 variableList -取决于引用的类型 std::visit .


    音符:

    pointer 作品 而不是 reference ,E.Q.:

    using foo = std::variant<std::atomic<double> *, std::atomic<int> *, std::string *>;
    
    auto bar() -> void
    {    
        std::atomic<double> atom_double;
        std::atomic<int>    atom_int;
        std::string         myString;
        ...
        std::map<std::string, ServerParameter> variableList(
            {
                { {"SomeText1" }, { &atom_double; true  } },
                { {"SomeText2" }, { &atom_int;    true  } },
                { {"SomeText3" }, { &myString;    false } },
            }
        );
        ...
    }
    

    然后是非常优雅的 STD:访问 :

    std::visit( visitHandler             
            {
                [&](std::atomic<double> * enumType) { *enumType = ..an assignment..; },
                [&](std::atomic<int> * enumType)    { *enumType = ..an assignment..; },
                [&](FaF::string * enumType)         { *enumType = ..an assignment..; },
            }, variantEntry );
    

    我的问题:

    1. 我做错什么了?我不明白错误信息,也没在网上找到任何东西。
    2. 什么是正确的声明 服务器参数 ?
    1 回复  |  直到 7 年前
        1
  •  4
  •   Mikhail Vasilyev    7 年前

    cppreference.com :

    不允许变量保存引用、数组或类型 无效。空的变体也是格式错误的( std::variant<std::monostate> 可以改为)。

    所以用指针代替是正确的。