变体:没有匹配的函数来调用“get”

Ard*_*niz 3 c++ templates variant variadic-templates c++17

这是我的代码:

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

class A {
public:
    virtual void Foo() = 0;    
};

class B : public A {
public:
    void Foo() override {
        std::cout << "B::Foo()" << std::endl;   
    }
};

class C :public A {
public:
    void Foo() override {
        std::cout << "C::Foo()" << std::endl;   
    }
};

template<typename... Args>
class D {
public:
    template<typename T>
    void Foo() {
        m_variant = T{};
    }

    void Bar() {
      std::get<m_variant.index()>(m_variant).Foo();
    }

private:
    std::variant<std::monostate, Args...> m_variant;
};

int main() {
    D<B, C> d;
    d.Foo<B>();
    d.Bar();

    d.Foo<C>();
    d.Bar();
}
Run Code Online (Sandbox Code Playgroud)

(参见wandbox.org

我收到错误no matching function for call to 'get',但我不明白为什么。std::variant::index()是 constexpr,所以这不是问题(我通过直接输入 value 进行测试1,但仍然是相同的错误)。
我有一个std::monostate防止空变体的方法(当没有参数时typename... Args

Jar*_*d42 6

m_variant.index()是一个运行时值(因为m_variant不是常量表达式)。

调度的方式是使用visitor,如下:

std::visit([](auto& v) { v.Foo(); }, m_variant);
Run Code Online (Sandbox Code Playgroud)

演示