【问题标题】:Passing a pointer of a variable as a parameter that is based on a template将变量的指针作为基于模板的参数传递
【发布时间】:2023-03-10 05:24:01
【问题描述】:

我可能使这比它需要的更混乱,但我试图找出处理模板并通过引用传递它们时的最佳做法。

我有一个名为IOQueue 的类模板。我在我的main 中创建了一个IOQueue<std::string>。我想将指针传递给将与所述队列交互的另一个类。这是我在看的内容:

main.cpp

IOQueue<std::string> *DecompressLogQueue;

int main(int argc, char** argv) 
{
    CompressFile cp(DecompressLogQueue);
    cp.Compress(9);

    return 0;
}

现在这就是我有点困惑的地方......在我的 CompressFile 类中,是否有一种更清洁、更合乎道德的方法来传递这个指针?这就是我现在看到的。

CompressFile::CompressFile(IOQueue<std::string> *DecompressLogQueue) 
{
    CompressFile::DecompressLogQueue = DecompressLogQueue;
}

如果我像这样在 CompressFile 中继承了我的 IOQueue 模板

class CompressFile : public IOQueue<string>
{
...

我不能做一些类似的事情

CompressFile::CompressFile(const T& DecompressLogQueue) 

我知道这可能无法编译。

谢谢

【问题讨论】:

  • 这里有问题吗?

标签: c++ class templates pointers


【解决方案1】:

如果您希望CompressFile 的构造函数只接受IOQueue&lt;T&gt;* 类型的参数,其中T 是非特定的,您可以使用这个:

class CompressFile
{
  public:
    template<typename T>
    CompressFile(IOQueue<T>* DecompressLogQueue)
    {
        // Will accept a pointer to an IOQueue with any template parameter.
        // ...
    }

    // ...  
};

如果你想让构造函数接受任何模板类型的参数,它有一个模板参数,你可以使用这个:

class CompressFile
{
  public:
    template<template<typename> class T, typename TParam>
    CompressFile(T<TParam>* DecompressLogQueue)
    {
        // Will accept a pointer to any class with one template parameter.
        // ...
    }

    // ...  
};

如果你想要更复杂的东西,你可能需要使用更复杂的模板魔法,可能涉及到来自&lt;type_traits&gt; 的一些助手。

注意,在这两种情况下,只有构造函数本身需要模板化; CompressFile 不需要任何模板参数即可工作。


现在,说了这么多,让我们看看你的其他问题:

在我的 CompressFile 类中,是否有更简洁、更符合道德的方法来传递此指针?

您可以尝试传递引用而不是指针,或者传递智能指针而不是原始指针。

template<template<typename> class T, typename TParam>
CompressFile::CompressFile(T<TParam>& DecompressLogQueue);

// ....

IOQueue<std::string> DecompressLogQueue;

int main(int argc, char** argv)
{
    CompressFile cp(DecompressLogQueue);
    // The compiler will handle the pointer syntax for you.
}

如果我像这样在 CompressFile 中继承了我的 IOQueue 模板

class CompressFile : public IOQueue<string>
{
...

我不能做一些类似的事情

CompressFile::CompressFile(const T& DecompressLogQueue) 

不幸的是,据我所知,C++ 缺少简单的语法、关键字或标准化宏来使用这样的父类类型,因此您仍然需要输入它。如果您想缩短名称,请尝试使用typedef。

typedef IOQueue<std::string> IOQSS;

CompressFile::CompressFile(const IOQSS& DecompressLogQueue);

如果这不是您要问的,能否请您澄清一下您的问题?

【讨论】:

    猜你喜欢
    • 2011-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-19
    相关资源
    最近更新 更多