c++ - 没有对象的模板打印成员变量

标签 c++ templates

这很奇怪(MSVC2012):

using namespace std;

class MyClass
{
public:

    int membervar;
};

template< int (MyClass::*var) > struct A 
{
   void print()
   {
       cout << var;
   }
};

int main(int argc, char *argv[])
{
   struct A <&MyClass::membervar> object;

   object.print();
}

此代码编译并实际计算出“1”。它从哪里得到它? membervar 属于什么对象?我以为我需要一个对象来访问数据成员

最佳答案

This code compiles and actually couts "1". Where does it get it?

发生的事情是:

int (MyClass::*var) = &MyClass::membervar;
cout << var;

因为没有采用流和成员指针的移位运算符,所以选择了另一个移位运算符:

std::ostream::operator<<(bool);

换句话说,它在将 var 转换为 bool 之后打印它。

关于c++ - 没有对象的模板打印成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15176853/

相关文章:

C++ vector 指针

c++ - 当鼠标悬停在边框上时,如何完全禁用调整窗口大小,包括调整大小图标?

C++映射问题

C++:const volatile 方法

php - Magento:<?php echo $this->getChildHtml ('content' ) 的内容 ?>

c++ - 类模板的模板参数列表中的类型/值不匹配

c++ - 模板化手动析构函数调用不起作用

c++ - 检测类型是否为函数

c++ - 了解 new-handler 的行为

c++ - C++ 的什么特性允许模板类在没有模板参数的情况下引用它们自己?