5

遵循问题如何检测类型是否可以流式传输到 std::ostream?我编写了一个特征类,说明是否可以将某种类型流式传输到 IO 流。直到现在我发现了一个问题,这个特性似乎运作良好。

我在使用 LLVM 的项目中使用代码,并且正在使用他们的 StringRef 类(在精神上与建议的 std::string_view 相似)。是该类的 Doxygen 文档的链接,如果需要,您可以从中找到它的声明头文件。由于 LLVM 没有提供 operator<< 来将 StringRef 对象流式传输到 std 流(它们使用自定义的轻量级流类),因此我编写了一个。

但是,当我使用 trait 时,如果我的自定义 operator<< 在 trait之后声明,它就不起作用(发生这种情况是因为我在一个标题中具有 trait,而在另一个标题中具有 operator<< 函数)。我曾经认为模板实例化中的查找从实例化点的角度来看是有效的,所以我认为它应该有效。实际上,正如您在下面看到的那样,使用另一个类及其自定义运算符<<,在特征之后声明,一切都按预期工作(这就是我现在才发现这个问题的原因),所以我不知道是什么让 StringRef特别的。

这是完整的例子:

#include <iostream>

#include "llvm/ADT/StringRef.h"

// Trait class exactly from the cited question's accepted answer
template<typename T>
class is_streamable
{
   template<typename SS, typename TT>
   static auto test(int)
      -> decltype(std::declval<SS&>() << std::declval<TT>(),
                  std::true_type());

   template<typename, typename>
   static auto test(...) -> std::false_type;

public:
   static const bool value = decltype(test<std::ostream,T>(0))::value;
};

// Custom stream operator for StringRef, declared after the trait
inline std::ostream &operator<<(std::ostream &s, llvm::StringRef const&str) {
   return s << str.str();
}

// Another example class
class Foo { };
// Same stream operator declared after the trait
inline std::ostream &operator<<(std::ostream &s, Foo const&) {
    return s << "LoL\n";
}

int main()
{
   std::cout << std::boolalpha << is_streamable<llvm::StringRef>::value << "\n";
   std::cout << std::boolalpha << is_streamable<Foo>::value << "\n";

   return 0;
}

与我的预期相反,这打印:

false
true

如果我在特征声明之前移动 StringRef 的 operator<<的声明,它会打印为 true。那么为什么会发生这种奇怪的事情,我该如何解决这个问题呢?

4

1 回答 1

1

正如 Yakk 所提到的,这只是 ADL:Argument Dependent Lookup。

如果您不想打扰,请记住,您应该始终在与其参数之一相同的命名空间中编写一个自由函数。在您的情况下,由于禁止将函数添加到std,这意味着将您的函数添加到llvm命名空间中。StringRef你需要用它来限定论点的事实llvm::是一个死的放弃。

函数解析的规则相当复杂,但作为一个简单的草图:

  • 名称查找:收集一组潜在的候选人
  • 重载决议:在潜力中挑选最佳候选人
  • 专业化解决方案:如果候选者是一个函数模板,检查任何可以应用的专业化

我们这里关心的名称查找阶段比较简单。简而言之:

  • 它扫描参数的命名空间,然后是它们的父级,......直到它到达全局范围
  • 然后继续扫描当前范围,然后是其父范围,......直到它到达全局范围

可能是为了允许阴影(就像任何其他名称查找一样),查找在遇到匹配的第一个范围内停止,并傲慢地忽略任何周围的范围。

请注意,using指令(using ::operator<<;例如)可用于从另一个范围引入名称。不过,这很麻烦,因为它把责任放在了客户身上,所以请不要依赖它的可用性作为草率的借口(我已经看到这样做了:x)。


阴影示例:此打印"Hello, World"不会引发歧义错误。

#include <iostream>

namespace hello { namespace world { struct A{}; } }

namespace hello { void print(world::A) { std::cout << "Hello\n"; } }

namespace hello { namespace world { void print(A) { std::cout << "Hello, World\n"; } } }

int main() {
    hello::world::A a;
    print(a);
    return 0;
}

中断搜索的示例:::hello::world产生了一个名为的函数print,因此即使它根本不匹配,它也会被挑选出来,并且::hello::print会是一个严格更好的匹配。

#include <iostream>

namespace hello { namespace world { struct A {}; } }

namespace hello { void print(world::A) { } }

namespace hello { namespace world { void print() {} } };

int main() {
    hello::world::A a;
    print(a); // error: too many arguments to function ‘void hello::world::print()’
    return 0;
}
于 2014-05-10T15:17:12.997 回答