【问题标题】:Code detecting both string and const char array检测字符串和 const char 数组的代码
【发布时间】:2012-10-24 21:51:21
【问题描述】:

我正在运行这两行代码,以便稍后添加到地图中:

o.add("-i", 800,             "int option");  
o.add("-w", "'switch on' option (no third parameter)");

要添加它们,我使用定义为的两个添加函数:

template<class T>
void add(std::string name, T value, std::string desc);
template<class T>
void add(std::string name, std::string desc);

第一个工作正常,并返回我想要的值,但如果我添加第二个,我会收到错误:

error: no matching function for call to ‘Opt::add(const char [3], const char [40])’

我的问题是为什么它在第一个字符串中正确使用了我的字符串,而我在第二个字符串中的字符串被认为是 const char 数组。

提前谢谢你。

【问题讨论】:

    标签: c++ string templates


    【解决方案1】:

    由于您没有在第二个重载中使用模板参数,请将其删除:

    template<class T>
    void add(std::string name, T value, std::string desc);
    
    void add(std::string name, std::string desc);
    

    可以在here找到一个工作示例。

    【讨论】:

    • 非常感谢,出于某种原因,我以为我稍后会在我的函数中使用 T,但事实证明我不是。不过,为了教育起见,为什么这会导致我的字符串被检测为 char 数组?
    • 因为它们字符数组。编译器看到add 的两个重载,一个带有三个参数,一个带有非自动推导的模板参数。由于调用与任何一个重载都不匹配,因此它向您显示了您尝试调用该函数的实际类型。在 C++ 中,与 C# 和 Java 不同,字符串文字具有 char 数组类型,而不是 std::string 类型,尽管它们可以自动转换为 std::string,因为 std::string 有一个采用 char 的非显式构造函数数组。
    • @Classtronaut,是的,它显示了你传入的类型。它仍然可以转换为不同的类型,就像第一个示例中发生的那样。
    【解决方案2】:

    错误信息很奇怪,但是要使用第二个重载,您需要显式指定模板参数(因为无法自动推断它):

    o.add<T>("-w", "'switch on' option (no third parameter)"); 
    

    或者,如果您在这种情况下实际上不需要模板参数,只需将其设为非模板方法即可。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-31
      • 2021-12-26
      • 2010-09-21
      • 2022-01-10
      • 1970-01-01
      相关资源
      最近更新 更多