[英]C++ understanding ADL
我編寫了此函數,以基於給定分隔符將對象的容器加入字符串。
template<typename Container>
std::string Join(Container const& input, char delimiter)
{
using std::to_string;
return std::accumulate(++std::begin(input), std::end(input), to_string(*std::begin(input))
, [&delimiter](std::string const& a, typename Container::const_reference b) { return a + delimiter + to_string(b); });
}
如您所見,我已經添加了using std::to_string;
當容器的類型已經是字符串時,使用ADL解決。
並且我已經實現了( to_string
和Join
in global namesapce):
const std::string& to_string(std::string const& str) { return str; }
現在考慮以下Join
調用:
Join(std::vector<std::string>{ "1", "2"}, ','); //Fail to compile
Join(std::vector<int>{ 1, 2}, ','); //Compiles
但是當我using ::to_string;
添加時using ::to_string;
Join
:
template<typename Container>
std::string Join(Container const& input, char delimiter)
{
using std::to_string;
using ::to_string;
return std::accumulate(++std::begin(input), std::end(input), to_string(*std::begin(input))
, [&delimiter](std::string const& a, typename Container::const_reference b) { return a + delimiter + to_string(b); });
}
這兩個調用都會編譯:
Join(std::vector<std::string>{ "1", "2"}, ',');
Join(std::vector<int>{ 1, 2}, ',');
有人可以解釋那里發生了什么嗎,全局to_string
發生某種“隱藏”?
using
,考慮的重載是通過在該名稱中查找而找到的重載,以及通過ADL發現的重載。
三種類型均不在根名稱空間中。
為了解決這個問題,寫
namespsce notstd {
std:string const& my_to_string(std::string const& in){return in;}
std::string my_to_string(std::string&& in){return std;:move(in);}
template<class T> std::string my_to_string( T const& in ){
using std::to_string;
return to_string(in);
}
}
這不支持sfinae的早期失敗。 這需要添加一個details
名稱空間和一些decltypes。
但是notstd::my_to_string
,您可以使用notstd::my_to_string
替換using和to_string。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.