c++ - 从 child 继承并调用 child 的功能在 visual studio 2013 中不起作用

标签 c++ templates visual-c++ inheritance

在下面的代码中:

#include <iostream>
using namespace std;

template<class T >
class Setting
{
public:
    Setting(Setting* instance){
        ((T*)instance)->write();
    };
    Setting(){ write(); };
    virtual void write(){ cout << "in parent\n"; }
};

class child :public Setting<child>
{
public:
    child() :Setting(this){};
    virtual void write(){ cout << "in child\n"; }
};
int main()
{
    child ch;
}

g++ 打印 "in child" 这正是我想要的。( http://coliru.stacked-crooked.com/a/4304ab99ebd894b3 )

但在 visual studio 2013 中输出是 “在父级” !!!( http://rextester.com/EMQ5448 )

为什么?有没有其他方法可以在 visual studio 中获得相同的结果?

最佳答案

"why?? Is there any alternative way for getting the same result in visual studio?"

因为编译器实现在处理这种语法时似乎有所不同。
好像 write()被声明为 virtual函数,VS2013 总是尝试从 vtable 中解析它,而不是使用(尚未)实例化的派生类中的方法(不尊重 static_cast<> )。

我在删除 virtual 时让您的示例正常工作来自您的关键字 write()函数声明,像这样

template<class T >
class Setting {
public:
    Setting(){ static_cast<T*>(this)->write(); };

    void write(){ cout << "in parent\n"; } // Note: No virtual
};

class child :public Setting<child> {
public:
    child() {};
    void write(){ cout << "in child\n"; }  // Note: No virtual
};

int main() {
    child ch;
}

虽然这行得通,但你真的应该服从,不要依赖从 child 建立的任何状态类构造函数,调用时 write来自基类。


您还想阅读有关 CRTP 的一些其他引用资料模式,并使用静态多态性(这就是避免 virtual )实际上是关于。

关于c++ - 从 child 继承并调用 child 的功能在 visual studio 2013 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27622130/

相关文章:

c++ - wxwidgets 自定义事件不会传播到父窗口

c++ - 使用 STL 容器的部分 C++ 模板特化

c++ - 如何将 sizeof() 运算符应用于非静态类成员方法?

c++ - (C++) 为相等元素的快速排序添加随机性

C++ 模板参数作为函数调用名称

c++ - 条件代码依赖于模板参数比较

c++ - 原始 int 指针与 vector::iterator<int>

c++ - char* 和 char[] 没有得到相同的输出

visual-c++ - ATL : Can't remove a method from a COM interface - ALWAYS reappears like magic

c++ - boost::asio 线程池与 io_service_per_cpu 设计