c++ - 使用 const char * 时如何将记录器与模板一起使用?

标签 c++ templates inheritance name-lookup

下面链接中的代码无法正常工作。我不知道我做错了什么。 https://coliru.stacked-crooked.com/a/f6ac59c7c20be10c

代码如下,错误信息在上面的链接中。

#include <iostream>
#include <string>

namespace Logger
{
    struct IStringable
    {
        virtual ~IStringable() {}
        virtual std::string ToString() const = 0;
    };

    std::string to_string(IStringable const& v) { return v.ToString(); }
    std::string to_string(const char* const& v) { return std::string(v); }

    template<class T>
    void log(T const& v)
    {
        using std::to_string;
        std::cout << "debug: " << to_string(v) << '\n';
    }
}

class Person : public Logger::IStringable {
public:
    Person(const std::string name) : _name(name) { }
    virtual std::string ToString() const { return _name; }
private:
    std::string _name;
};

int main()
{
    Person p("Alice");
    double d = 0.0;
    const char* c = "Some words";

    Logger::log(p); // Works
    Logger::log(d); // Works
    Logger::log(c); // Error

}

g++ -std=c++17 -O2 -Wall -Wextra -Werror -pedantic main.cpp && ./a.out
main.cpp: In instantiation of 'void Logger::log(const T&) [with T = const char*]':
main.cpp:39:18:   required from here
main.cpp:19:44: error: no matching function for call to 'to_string(const char* const&)'
         std::cout << "debug: " << to_string(v) << '\n';
                                   ~~~~~~~~~^~~

最佳答案

在函数体中使用 using std::to_string; ,命名空间 Logger 中的名称 to_string 将不会通过 name lookup 找到;当在函数范围内找到名称并且没有进一步检查范围时,它将停止。

请注意,对于 IStringable to_string(IStringable const& v) 可以通过 ADL 找到,它不适用于 const char* 等内置类型。

1) For arguments of fundamental type, the associated set of namespaces and classes is empty

您可以将 using std::to_string; 移出函数体。例如

using std::to_string;
template<class T>
void log(T const& v)
{
    std::cout << "debug: " << to_string(v) << '\n';
}

LIVE

关于c++ - 使用 const char * 时如何将记录器与模板一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56476321/

相关文章:

c++ - 如何从 HBITMAP 获取 RGBQUAD?

sql - 仅将表用于多重继承是一种不好的做法吗?

database - 在数据库中使用继承的优点和缺点是什么

c# - 从抽象父类调用泛型列表上的方法

c++ - 在不使用自旋锁的情况下在空队列上暂停线程

c++ - 如何获取数组的大小?

c++ - 将动态变量添加到 url

c++ - 模板推导不适用于函数指针引用

c++ - 需要了解函数模板解析规则

c++ - 如何让编译器推断模板的返回类型?