从模板派生类访问方法,而不使用c ++中的虚函数? [英] Accessing a method from a templated derived class without using virtual functions in c++?

查看:151
本文介绍了从模板派生类访问方法,而不使用c ++中的虚函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何解决这个问题?我显然不能让value()方法虚拟,因为我不知道什么类型它是预先的,并且可能不知道这当从b访问方法:

How do I get around this? I clearly cannot make the value() method virtual as I won't know what type it is beforehand, and may not know this when accessing the method from b:

class Base
{
public:
    Base() { }
    virtual ~Base() { }
private:
    int m_anotherVariable;
};

template <typename T>
class Derived : public Base
{
public:
    Derived(T value) : m_value(value) { }
    ~Derived() { }

    T value() { return m_value; }
    void setValue(T value) { m_value = value; }
private:
    T m_value;
};

int main()
{
    Base* b = new Derived<int>(5);

    int v = b->value();

    return 0;
}

编译错误:

error: 'class Base' has no member named 'value'


推荐答案

此语句:

int v = b->value();

变量'b'正在被调试,因为它是Derived< int> />
所以告诉编译器:

The variable 'b' is being trated like it is an object of Derived<int>.
So tell the compiler:

int v = dynamic_cast<Derived<int>*>(b)->value();

注意:如果b不是Derived< int>

因此,以下内容可能更安全:

Note: If b is not a Derived<int> the result of the cast is NULL.
So the following would probably be safer:

Derived<int>*  d = dynamic_cast<Derived<int>*>(b);
if (d)
{
    int v = d->value();
}
else
{
    // Error
}


b $ b

或者通过使用引用,你得到一个bad_cast异常抛出:

Alternatively by using references you get a bad_cast exception thrown:

// Throw bad_cast on failure.
Derived<int>& d = dynamic_cast<Derived<int>&>(*b);
int v = d->value();

或者是好的和模糊的,我们可以一行。

Or to be nice and obscrure we can do it one line.

// Assign v or throw bad_cast exception:
int v = dynamic_cast<Derived<int>&>(*b).value();

但我想你可以实现你想使用boost :: any

But I think you can achieve what you are trying to do with the boost::any

int main()
{
    boost::any   b(5);

    int    v = boost::any_cast<int>(b);

    b        = 5.6; // double
    double d = boost::any_cast<double>(b);
}

这篇关于从模板派生类访问方法,而不使用c ++中的虚函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆