如何在访问变体时编写重载的忽略功能

问题描述 投票:0回答:1

下面是我的代码:

#include <iostream>
#include <string>
#include <vector>
#include <variant>

struct ignore
{
    template <typename T>
    void operator()([[maybe_unused]]const T&)
    {
        std::cout << "other type" << std::endl;
    }
};

template <class... Ts>
struct overloaded_ignore : ignore, Ts...
{
    overloaded_ignore(Ts...) : ignore(){}
    using Ts::operator()...;
    using ignore::operator();
};

int main()
{
    std::variant<int,float,std::string> my_var = std::string("helloworld");
    // std::variant<int,float,std::string> my_var = 5.0F;
    // std::variant<int,float,std::string> my_var = 3;


    std::visit(overloaded_ignore{
        [](const int& t)
        {
            std::cout << "int var: " << t << std::endl;
        },
        [](const std::string& t)
        {
            std::cout << "string var: " << t << std::endl;
        }
        }, my_var);

    
    return 0;
}

我期望输出“string var: helloworld”,但是输出的是“其他类型”。 如何解决这个问题。 请注意,忽略的“operator ()”是必需的。

字符串变量:需要 helloworld。

c++ templates variant
1个回答
0
投票

您可以限制

ignore
的呼叫操作员,例如

template<class... Ts>
struct ignore
{
    template <typename T>
      requires (!std::is_invocable_v<Ts, const T&> && ...)
    void operator()([[maybe_unused]]const T&)
    {
        std::cout << "other type" << std::endl;
    }
};

template <class... Ts>
struct overloaded_ignore : ignore<Ts...>, Ts...
{
    overloaded_ignore(Ts...) { }
    using Ts::operator()...;
    using ignore<Ts...>::operator();
};
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.