c++ - 错误 : "2 overloads have similar conversions"

标签 c++ templates c++11 overloading

编辑: 在我写问题时,我注意到方法 std::string GetNodeValue(const std::string& nodePath, const char * defaultValue)不是常数。正如 LogicStuff 在他的评论中也提到的那样,添加了 const限定条件解决了歧义。

我知道这个问题已经被提出并得到了正确的回答 here和其他几次。我理解潜在的问题,但我不太明白为什么会在这种特殊情况下发生,它唤醒了我好奇的 self 。

我有以下类(class):

class ConfigurationReader
{
public:
    // ...   
    std::string GetNodeValue(const std::string& nodePath, const char * defaultValue)
    {
        const std::string temp(defaultValue);
        return GetNodeValue(nodePath, temp); 
    }    

    template <typename T> T GetNodeValue(const std::string & nodePath, T defaultValue) const 
    {
        boost::optional<T> nodeValue = configuration.getNodeValueNothrow<T>(nodePath);
        if ( nodeValue ) 
        {
            return *nodeValue;
        }
        LogConfigurationProblemsCri(logger, "Node not found: " << nodePath << ", Default value: " << defaultValue);
        return defaultValue;
    }
    // ...    
};

模板方法也有几个针对类型的特殊化 int16_t , uint16_t , 等等直到 uint64_t .

它在使用时就像一个魅力:

string someValue = configurationReaderPtr->GetNodeValue("some_noe", "");
uint32_t otherValue = configurationReaderPtr->GetNodeValue("other_node", 11000);
bool yetAnother = configurationReaderPtr->GetNodeValue("other_node", true);

除了一种情况:

uint32_t otherValue = configurationReaderPtr->GetNodeValue("other_node", 0);

我不断收到的错误是: “2 个重载具有相似的转换 可以是“std::string ConfigurationReader::GetNodeValue(const std::string &,const char *)”或“uint32_t ConfigurationReader::GetNodeValue(const std::string &,uint32_t ) const'"

我尝试转换“默认”值:uint32_t(0) , static_cast<uint32_t>(0) , 0U没有任何运气。

我应该指出,我已经找到了一个解决方法:

uint32_t otherValue = 0;
otherValue = configurationReaderPtr->GetNodeValue("other_node", otherValue);

但这并不能回答我的好奇心。我目前正在使用 Microsoft Visual Studio 2012 Express 和 boost 1.54 库。

有什么想法吗?

最佳答案

这是因为 0 是空指针的字面量(在现代 C++ 中被“nullptr”取代)。

所以 0 可以是 int 或空指针,尤其是 char*

编辑以添加一些引用: 您可以在标准中找到它作为

4.10 Pointer conversions A null pointer constant is an integer literal (2.13.2) with value zero or a prvalue of type std::nullptr_t

(最后一个是对nullptr的引用)

关于c++ - 错误 : "2 overloads have similar conversions",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35162259/

相关文章:

c++ - glsl 错误 : "v_color" not declared as an output from the previous stage while trying to render wtih tesselation shaders

c++ - 在 C++ 中创建实例时出现错误

c++ - 将函数作为参数传递以简化线程创建

c++ - 如何将从模板参数派生的编译时信息添加到模板?

c++ - 迭代器类型的模板

c++ - 1.0 是 std::generate_canonical 的有效输出吗?

c++ - 当 ParamType 既不是指针也不是引用时自动类型推导

c++ - 用 C/C++ 编写的语法高亮库

html - Joomla 不在前端显示图像

c++ - void* 和 char* 的区别