会员专业化不匹配任何模板声明

发布于 2025-01-28 19:19:03 字数 1391 浏览 2 评论 0原文

下面的代码编译除行之外,

template <> std::map<std::string, std::function<Goo*(Foo*)>>& Factory::getMap<Goo, Foo*>() {
    return gooMap;
}

这里有什么问题,如何修复?编译器(GCC 11.2)指出,成员专业化与任何模板声明不匹配,但对我来说看起来确实如此。

#include <map>
#include <functional>

struct Foo;  struct Goo;

struct Factory {
    std::map<std::string, std::function<Foo*()>> fooMap;
    std::map<std::string, std::function<Goo*(Foo*)>> gooMap;
    
    template <typename T, typename U, typename... Args>
    std::function<T*(Args&&...)> create() {
        return [](Args&&... args) -> T* { return new U(std::forward<Args>(args)...); };
    }
    
    template <typename T, typename... Args>
    std::map<std::string, std::function<T*(Args&&...)>>& getMap();
    
    template <typename T, typename U, typename... Args>
    void registerFunction (const std::string& name) {
        getMap<T, Args...>()[name] = create<T, U, Args...>();
    }
};
template <> std::map<std::string, std::function<Foo*()>>& Factory::getMap<Foo>() {
    return fooMap;
}
template <> std::map<std::string, std::function<Goo*(Foo*)>>& Factory::getMap<Goo, Foo*>() {
    return gooMap;
}

int main() {}

The code below compiles except for the lines

template <> std::map<std::string, std::function<Goo*(Foo*)>>& Factory::getMap<Goo, Foo*>() {
    return gooMap;
}

What is wrong here, and how would it be fixed? The compiler (GCC 11.2) states that the member specialization does not match any template declaration, but to me it looks like it does.

#include <map>
#include <functional>

struct Foo;  struct Goo;

struct Factory {
    std::map<std::string, std::function<Foo*()>> fooMap;
    std::map<std::string, std::function<Goo*(Foo*)>> gooMap;
    
    template <typename T, typename U, typename... Args>
    std::function<T*(Args&&...)> create() {
        return [](Args&&... args) -> T* { return new U(std::forward<Args>(args)...); };
    }
    
    template <typename T, typename... Args>
    std::map<std::string, std::function<T*(Args&&...)>>& getMap();
    
    template <typename T, typename U, typename... Args>
    void registerFunction (const std::string& name) {
        getMap<T, Args...>()[name] = create<T, U, Args...>();
    }
};
template <> std::map<std::string, std::function<Foo*()>>& Factory::getMap<Foo>() {
    return fooMap;
}
template <> std::map<std::string, std::function<Goo*(Foo*)>>& Factory::getMap<Goo, Foo*>() {
    return gooMap;
}

int main() {}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文