c++ - 显式运算符 << 选择 'wrong' 重载

标签 c++ c++11 variadic-templates

我正在玩弄可变参数模板,并根据 this answer 写了这篇文章:

template <size_t... I>
void print(seq<I...>)
{
    decltype(std::cout) * dummy[sizeof...(I)] = { &(std::cout << I << ' ')... };
}

因为 std::cout::operator<<有一个返回类型,它可以被存储,所以不需要 ( ,0)逗号技巧。

现在,为了关闭“unused variable 'dummy'”警告并打印换行符,我尝试了以下语句,但它们没有按照我的意愿进行:

dummy[0]->operator <<('\n'); // prints 10

(显然称为 operator<<(int) 而不是 operator<<(char)

dummy[0]->operator <<("\n"); // prints a pointer

(显然称为 operator<<(const void*) 而不是 operator<<(const char*)

最后,我不得不写

*dummy[0] << '\n';             // prints a newline as desired

我的问题是,为什么选择了“错误的”重载?

最佳答案

选择“错误的”重载是因为 only some overloadsstd::ostream 的成员类(class)。 char 的重载和 const char*不是 std::ostream 的成员, 但是 free functions ,所以,在

*dummy[0] << '\n';

依赖于参数的查找将找到 operator<<(std::ostream&, char) , 但在

dummy[0]->operator <<('\n');

仅考虑成员函数,结果为 std::ostream::operator<<(int)被调用。

关于c++ - 显式运算符 << 选择 'wrong' 重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33210688/

相关文章:

c++ - "\b"作为字符添加到字符串中

c++ - 将图像重新整形为 3 列矩阵 matlab 与 openCV

c++ - 为什么 std::function 不能接受推导类型作为其模板参数?

c++ - unique_ptr 和 shared_ptr 的奇怪段错误

c++ - 正确使用 std::enable_if 或如何替换它

c++ - 可变参数,它们都是模板类型的特化

c++ - 对可变参数模板函数的误解

c++ - 在可变参数模板中使用声明

c++ - 状态机设计

c++ - 同时支持C++98和C++11