【问题标题】:c++ template issue [closed]c ++模板问题[关闭]
【发布时间】:2012-11-05 16:08:35
【问题描述】:

我目前正在使用本教程中给出的类:http://www.dreamincode.net/forums/topic/183191-create-a-simple-configuration-file-parser/

最初它运行良好,但由于我将单个源文件拆分为单独的头文件和 cpp 文件,我无法调用 getValueOfKey 函数

标题:

#ifndef CONFIGFILE_H
#define CONFIGFILE_H

#include <iostream>
#include <string>
#include <sstream>
#include <map>
#include <fstream>
#include <typeinfo>

class ConfigFile
{
private:
        std::map<std::string, std::string> contents;
    std::string fName;
    void removeComment(std::string &line) const;
    bool onlyWhitespace(const std::string &line) const;
    bool validLine(const std::string &line) const;
    void extractKey(std::string &key, size_t const &sepPos, const std::string &line) const;
    void extractValue(std::string &value, size_t const &sepPos, const std::string &line) const;
    void extractContents(const std::string &line);
    void parseLine(const std::string &line, size_t const lineNo);
    void ExtractKeys(); 
public:
    ConfigFile(const std::string &fName);
    bool keyExists(const std::string &key) const;
    template <typename ValueType>
    ValueType getValueOfKey(const std::string &key, ValueType const &defaultValue) const;
};


#endif  /* CONFIGFILE_H */

cpp:

#include "ConfigFile.h"

std::map<std::string, std::string> contents;
std::string fName;

template <typename T>
static std::string T_to_string(T const &val)
{
    std::ostringstream ostr;
    ostr << val;

    return ostr.str();
}

template <typename T>
static T string_to_T(std::string const &val)
{
    std::istringstream istr(val);
    T returnVal;
    if (!(istr >> returnVal))
        std::cout << "CFG: Not a valid " << (std::string)typeid (T).name() << " received!\n" << std::endl;

    return returnVal;
}

template <>
std::string string_to_T(std::string const &val)
{
    return val;
}

void ConfigFile::removeComment(std::string &line) const
{
    if (line.find(';') != line.npos)
        line.erase(line.find(';'));
}

bool ConfigFile::onlyWhitespace(const std::string &line) const
{
    return (line.find_first_not_of(' ') == line.npos);
}

bool ConfigFile::validLine(const std::string &line) const
{
    std::string temp = line;
    temp.erase(0, temp.find_first_not_of("\t "));
    if (temp[0] == '=')
        return false;

    for (size_t i = temp.find('=') + 1; i < temp.length(); i++)
        if (temp[i] != ' ')
            return true;

    return false;
}

void ConfigFile::extractKey(std::string &key, size_t const &sepPos, const std::string &line) const
{
    key = line.substr(0, sepPos);
    if (key.find('\t') != line.npos || key.find(' ') != line.npos)
        key.erase(key.find_first_of("\t "));
}

void ConfigFile::extractValue(std::string &value, size_t const &sepPos, const std::string &line) const
{
    value = line.substr(sepPos + 1);
    value.erase(0, value.find_first_not_of("\t "));
    value.erase(value.find_last_not_of("\t ") + 1);
}

void ConfigFile::extractContents(const std::string &line)
{
    std::string temp = line;
    temp.erase(0, temp.find_first_not_of("\t "));
    size_t sepPos = temp.find('=');

    std::string key, value;
    extractKey(key, sepPos, temp);
    extractValue(value, sepPos, temp);

    if (!keyExists(key))
        contents.insert(std::pair<std::string, std::string > (key, value));
    else
        std::cout << "CFG: Can only have unique key names!\n" << std::endl;
}

void ConfigFile::parseLine(const std::string &line, size_t const lineNo)
{
    if (line.find('=') == line.npos)
        std::cout << "CFG: Couldn't find separator on line: " << T_to_string(lineNo) << "\n" << std::endl;

    if (!validLine(line))
        std::cout << "CFG: Bad format for line: " << T_to_string(lineNo) << "\n" << std::endl;

    extractContents(line);
}

void ConfigFile::ExtractKeys()
{
    std::ifstream file;
    file.open(fName.c_str());
    if (!file)
        std::cout << "CFG: File " << fName << " couldn't be found!\n" << std::endl;

    std::string line;
    size_t lineNo = 0;
    while (std::getline(file, line))
    {
        lineNo++;
        std::string temp = line;

        if (temp.empty())
            continue;

        removeComment(temp);
        if (onlyWhitespace(temp))
            continue;

        parseLine(temp, lineNo);
    }

    file.close();
}

ConfigFile::ConfigFile(const std::string &fName)
{
    this->fName = fName;
    ExtractKeys();
}

bool ConfigFile::keyExists(const std::string &key) const
{
    return contents.find(key) != contents.end();
}

template <typename ValueType>
ValueType ConfigFile::getValueOfKey(const std::string &key, ValueType const &defaultValue = ValueType()) const
{
    if (!keyExists(key))
        return defaultValue;

    return string_to_T<ValueType> (contents.find(key)->second);
}

我尝试使用与单个文件相同的方法调用它,例如 std::cout &lt;&lt; Config.getValueOfKey&lt;std::string&gt;("test");,但现在我收到以下编译器错误

main.cpp: In function 'int main(int, char**)':
main.cpp:29:71: error: no matching function for call to 'ConfigFile::getValueOfKey(const char [5])'
main.cpp:29:71: note: candidate is:
In file included from main.h:17:0,
                 from main.cpp:9:
ConfigFile.h:35:12: note: template<class ValueType> ValueType ConfigFile::getValueOfKey(const string&, const ValueType&) const
ConfigFile.h:35:12: note:   template argument deduction/substitution failed:
main.cpp:29:71: note:   candidate expects 2 arguments, 1 provided

鉴于我对模板的掌握不佳,我无法真正看到这个错误试图告诉我什么,我尝试传递直接字符串而不是 char 数组,但无济于事。任何帮助或解释将不胜感激,在过去的几个小时里,我的头在桌子上钻了一个漂亮的洞。

【问题讨论】:

  • 这段代码的绝大部分与问题无关。请在缩小问题范围时发布您为自己制作的 5-10 行测试用例。
  • @Robᵩ 这不是链接器错误(还),它是方法声明中缺少的默认参数。
  • @Robᵩ:它们完全不相关。
  • 是的,我错了。可悲的是,没有一个选项可以撤销一个接近投票。

标签: c++ templates


【解决方案1】:

您声明了采用 2 个参数的方法:

ValueType getValueOfKey(const std::string &key, ValueType const &defaultValue) const;
//                                          |                           |
//                                   first parameter             second parameter

并且只提供一个:

Config.getValueOfKey<std::string>("test");

我还没有遇到一个编译器可以在没有任何帮助的情况下猜出你的意思。

您需要将默认值移到头文件中,并在其中声明方法:

ValueType getValueOfKey(const std::string &key, ValueType const &defaultValue = ValueType()) const;
    //                                          |                           |
    //                                   first parameter             second parameter

之后您可能会收到链接器错误,因此您可能需要检查this。

【讨论】:

  • 社区驱动的so++ 怎么样?它将 SO 问题转化为可执行代码,并具有水晶球代码推导功能。
  • 我还没有遇到一个 C++ 标准,它允许在没有任何帮助的情况下猜测你的意思。
  • @KerrekSB:嗯,我们已经完成了一半......
  • 啊,我的印象是默认必须进入定义,谢谢
  • @LightnessRacesinOrbit - 我还没有遇到一个 C++ 标准,它允许在没有任何帮助的情况下猜测你的意思。 这正是任何体面的编译器都会做的事情。一个好的编译器会尝试理解格式错误的输入,然后继续执行以检测和报告多个错误。处理在输入的第一个错误时停止的工具链是非常痛苦的。
猜你喜欢
  • 1970-01-01
  • 2011-11-22
  • 2017-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-14
  • 1970-01-01
相关资源
最近更新 更多