3

我正在尝试制作一个Template可以存储模板值的 C++ 类。但是,我需要在知道模板值的类型之前创建指向此类的指针。为此,我创建了一个Base模板类继承自的抽象类。我创建指向 的指针Base,当它们被分配时,我使用basePtr = new Template<TYPE>.

这里的问题在于给Template. 我能想到的每一种方法(我想使用重载的赋值运算符)都需要一个带有模板数据类型的方法作为形式参数。因为Template对象只能通过Base指针访问,所以我必须在Base. 但是,虚方法不能包含模板数据类型,并且Base' 签名中的虚方法必须与Template' 方法匹配。

这是我要做的一个例子:

class Base {
    public:
        /* THIS IS ILLEGAL - can't have template virtual method
        template <class V>
        virtual void operator =(const V& newValue) = 0;
        */
};

template <class ValueType>
class Template : public Base {
    private:
        ValueType *value;
    public:
        void operator =(const ValueType& newValue) {
            *value = newValue;
        }
};

int main() {
    Base *theObject;                  // Datatype for template not known 
    theObject = new Template<string>; // At this point, it will be known

    // NOW, THIS DOESN'T WORK - no virtual assignment overload in Base
    *theObject = "Hello, world!";

    return 0;
}

如果我以完全错误的方式进行此操作,并且如果我的方法很愚蠢,我深表歉意——这是我第一次尝试真正的 OOD。有没有办法解决我没有看到的这个问题?我知道我可以创建一长串纯虚函数,Base用不同的输入类型重载赋值运算符,如下所示:

virtual void operator =(const string& newValue) = 0;
virtual void operator =(const int& newValue) = 0;
virtual void operator =(const long& newValue) = 0;
...

但是,我希望用户能够在Template::value.

4

2 回答 2

1

实现您想要实现的目标的一种方法是使用Boost.Any(一个著名的仅标头库)。下面是一个演示。代码是一步一步注释的,所以你应该能看懂,下面一个活生生的例子:

#include <stdexcept>       // Standard header for exception classes
#include <string>          // Standard header for std::string
#include <boost/any.hpp>   // The Boost.Any library header
#include <iostream>        // This program prints some output

class Base
{
public:
    virtual void operator = (boost::any val) = 0;
    //                       ^^^^^^^^^^
    //                       This can hold (almost) "any" value

    // You need a virtual destructor if you want to delete objects
    // of subclasses of this class through a pointer to this class!
    virtual ~Base() { }
};

template <class ValueType>
class Template : public Base
{
private:
    ValueType value;
//  ^^^^^^^^^
//  I do not see why using a pointer in this case. Manual memory
//  management just complicates things. However, if your really
//  need to do it and your really know what you're doing, go ahead.
//  Just remember to delete your pointer at destruction and not to
//  dereference it before it points to an allocated object (in your
//  original text, both of these things are NOT done correctly).
public:
    virtual void operator = (boost::any val)
    {
        // Attempt a cast to detect if the value we are trying to
        // assign to this object is of the appropriate type...
        ValueType* pVal = boost::any_cast<ValueType>(&val);
        if (pVal == nullptr)
        {
            // ...it is not! Throw an exception...
            throw std::logic_error("Incompatible type");
        }

        // The value is OK: assign it...
        value = *pVal;
    }
};

int main()
{
    Base *theObject;
    theObject = new Template<std::string>;

    try
    {
        // This assignment will succeed...
        // Wrapping the string literal in a std::string object is necessary
        // because boost::any cannot be initialized from an array (and in C++
        // string literals are arrays of characters).
        *theObject = std::string("Hello, world!");

        // This assignment will fail!
        *theObject = 1;
    }
    catch (std::logic_error const& e)
    {
        // Handle the exception...
        std::cout << e.what();
    }

    delete theObject; // <=== DON'T FORGET THIS!

    return 0;
}
于 2013-02-28T01:56:41.177 回答
0

听起来 boost::any 有点像你正在寻找的东西。不需要奇怪的继承层次结构,它可以自己存储任意类型(有一定的限制)。

现在我关心的是你打算如何重新获得你的价值?您的代码如何确定该单元格是否包含 int、std::string 或其他一些它以前从未听说过的用户定义类型,而不是尝试将其 any_cast 到某个类型列表(如果类型未列出...)?

于 2013-02-28T02:12:38.160 回答