模板专业和STD :: MAP

Template Specialization and std::map

本文关键字:STD MAP      更新时间:2023-10-16

我正在尝试使用相应的文本和呼叫功能创建Code的地图。我会收到编译错误,我无法弄清楚我的代码,std::map初始化是什么问题。有人可以解释一下我在做什么错,我该如何解决:

#include <iostream>
#include <vector>
#include <string>
#include <functional>
#include <utility>
#include <map>
namespace mvs
{
    enum Code
    {
        Code0  = -1,
        Code1  = -2,
        Code2  = 1,
        CodeCount
    };
}
class CompositeFile
{
public:
    CompositeFile(std::string const& name) : name_(name) {}
    template <typename T>
    long readEx(mvs::Code code, std::vector<T>& buffer)
    {
         return 0;
    }
    std::string readString(mvs::Code code)
    {
        return {};
    }
private:
    std::string name_;
};
namespace mh
{
     class CompositeFileEx : public CompositeFile
     {
     public:
        CompositeFileEx(std::string const& name) : CompositeFile(name) {}
        template <typename T>
        std::string get(mvs::Code code)
        {
            std::vector<T> buffer;
            readEx(code, buffer);
            return {};
        }
    private:
        typedef std::pair<std::string, std::function<std::string(mvs::Code)> > pair_type;
         **std::map<mvs::Code, pair_type> map_ =
         {
             { mvs::Code1, { "Code1", get<char>(mvs::Code1) } }
         };**
     };
     template <>
     std::string CompositeFileEx::get<char>(mvs::Code code)
     {
         return readString( code );
     }
}
int main(int argc, char** argv)
{
    return 0;
}

仔细查看如何定义对:

std::pair<std::string, std::function<std::string(mvs::Code)>>

第二个元素是std::function<std::string(mvs::Code)>。构造时,您应该将可呼出的对象作为对的第二个参数。

表达式get<char>(mvs::Code1)的类型不是将代码作为参数并返回字符串的可呼叫对象。表达式导致字符串直接。

要解决此问题,您应该发送一个将代码作为参数的lambda函数,然后返回get

的结果