下面是我的代码:
#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。
您可以限制
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();
};