受到This示例的启发,即受此特定代码的启发
// ...
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
// ...
std::visit(overloaded {
[](auto arg) { std::cout << arg << ' '; },
[](double arg) { std::cout << std::fixed << arg << ' '; },
[](const std::string& arg) { std::cout << std::quoted(arg) << ' '; },
}, v);
...我试图定义类型为overloaded
的类的成员,但偶然发现了困难,我认为(但不确定)是由于编译器无法推断模板的参数而引起的。
template<class ...Ts>
struct overloaded : Ts... {
using Ts::operator()...;
constexpr overloaded(Ts... ts) : Ts(ts)... {}
};
struct as{};
class phil_t {
int i;
overloaded o { [&](as&) {cout << i << "as"; } }; // <-- HERE
};
这是我收到的输出:
../../variant.hpp:21:5: error: invalid use of template-name ‘overloaded’ without an argument list
overloaded o { [&](as&) {cout << i << "as"; } };
^~~~~~~~~~
值得一提的是,当我使用相同的方法实例化一个不在类内部的对象时,一切都会顺利进行。
void varnt() {
int i = 42;
auto o = overloaded( [&](as&) {cout << i << "as"; } );
}
非常感谢您提供一些解决方法的建议,解释或提示。
谢谢。
您不能具有不是某些特定类型的成员变量,这是您要在phil_t
中尝试执行的操作,因为overloaded
是指模板而不是类型。