gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 15:30:05 25 4
gpt4 key购买 nike

下面链接中的代码无法正常工作。我不知道我做错了什么。 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com