【问题标题】:Using the PIMPL idiom with member function templates (without knowing all possible data types up-front)将 PIMPL 成语与成员函数模板一起使用(无需预先知道所有可能的数据类型)
【发布时间】:2019-06-08 02:44:52
【问题描述】:

我正在尝试使用 PIMPL 习惯用法实现一个通用接口,它需要一些模板成员函数来为 ANY 类型提供功能。问题是我找不到任何方法来支持在 PIMPL 习惯用法中使用模板函数,而无需预先声明该函数可能使用的所有可能类型。

查看相关问题:Pimpl Idiom with template member function

对该问题的公认答案建议明确定义将与模板一起使用的每种类型。这并不总是实用的。考虑以下示例:

example.h

#ifndef EXAMPLE_H
#define EXAMPLE_H

#include <memory>

class Example
{
public:
    Example();
    ~Example();

    // Generic template function in the interface
    template <typename T>
    void PrintData(const T& data) const;

private:
    struct Impl;
    std::unique_ptr<Impl> m_impl;
};

#endif

example.cpp

#include "example.h"
#include <iostream>

// Private implementation
struct Example::Impl
{
    template <typename T>
    void PrintData(const T& data) const
    {
        std::cout << data << std::endl;
    }
};

// Note: using C++11 so "make_unique" is not available
Example::Example() : m_impl(new Impl()) {}
Example::~Example() = default;

// Forward the method call to the implementation
template <typename T>
void Example::PrintData(const T& data) const
{
    m_impl->PrintData(data);
}

// Don't want to have to explicitly state all types...
// this is not practical because "PrintData" should work for ANY printable type.

// Uncommenting the line below will allow this example to compile,
// but it will only compile when used with "int" data.
//template void Example::PrintData(const int& data) const;

ma​​in.cpp

#include "example.h"

int main()
{
    Example ex;
    ex.PrintData(42);
}

尝试编译它会失败并出现未定义的引用错误:

g++ -std=c++11 -o main main.cpp example.cpp
/tmp/cc6IhZsx.o: In function `main':
main.cpp:(.text+0x2b): undefined reference to `void Example::PrintData<int>(int const&) const'
collect2: error: ld returned 1 exit status

这个例子在接口中提供了一个非常通用的函数,它应该适用于任何可打印的类型。这带来了一个问题,因为在编译时我们无法预测此函数将用于的所有类型。

如何让这样的函数与 PIMPL 习语(或其他创建“compiler firewall”的方法)一起使用

请注意,此示例是有意为演示问题而设计的。在现实世界中,我的类在接口中包含更复杂的模板函数,需要处理多种类型。因此,我无法将这些类置于 PIMPL 惯用语提供的编译器防火墙后面。

我愿意考虑 PIMPL 成语的替代方案,如果存在任何此类事情,可以达到预期的效果。

【问题讨论】:

  • 你确定你真的想要 Pimpl 而不是 CRTP?
  • 如果你必须使用 PIMPL 成语,你能做的最好的就是某种类型的擦除。也许std::function 或提议的std::function_ref 会让你做你需要的。
  • 我将研究 CRTP 和类型擦除,我对两者都不是特别熟悉。
  • 你真的想用模板的 pimpl 隐藏什么?
  • @JesperJuhl 您仍然需要事先知道实现内部的类型,以便知道如何将其转换回原始类型以进行打印。

标签: c++ templates pimpl-idiom


【解决方案1】:

如果您必须使用 PImpl 惯用语并且必须支持任何类型,那么您能做的最好的事情就是键入擦除行为。这允许您隐藏实现的部分,但不是全部。

对于简单的情况,std::function 或建议的std::function_ref 可以工作:

#include <memory>
#include <ostream> // We must define some of the behavior in the header file.
#include <functional> // for std::function

class Example
{
public:
    Example();
    ~Example();

    // Generic template function in the interface
    template <typename T>
    void PrintData(const T& data) const;

private:
    struct Impl;
    std::unique_ptr<Impl> m_impl;

    // Some alternatives:
    // Some cost:
    void PrintDataImpl(const void* obj,
         const std::function<void(std::ostream&, const void*)>&) const;
    // Not yet standardized:
    void PrintDataImpl(const void* obj,
         std::function_ref<void(sstd::ostream&, const void*)>) const;
    // C-style:
    void PrintDataImpl(const void* obj,
         void(*fn)(std::ostream&, const void*)) const;
};

template <typename T>
void Example::PrintData(const T& data) const
{
    // std::function is expensive, but in this case, we fit in the small buffer
    // optimization as a lambda with no captures.
    // If we used `std::function_ref`, this would be cheaper.
    // If we used the C-style, the lambda cannot capture anything.
    PrintDataImpl(&data, [](std::ostream& out, const void* obj) {
        out << *static_cast<const T*>(obj);
    });
}


// In Example.cpp:
void Example::PrintDataImpl(const void* obj,
     const std::function<void(std::ostream&, const void*)>& fn) const
{
    // Call the function to apply the one piece of type-erased behavior.
    fn(std::cout, obj);
    std::cout << std::endl;
}

【讨论】:

  • 但是你不会在 pimpl 中隐藏任何东西......(例如,&lt;iostream&gt; 已包含在标题中)。
  • 如果你这样做,它确实看起来好像现在已经公开并且不再隐藏在 PIMPL 中。如果不是这种情况,你能解释一下吗?我不认为我完全理解。
  • @Jarod42 没错。这仅适用于更复杂的情况,即您有其他要隐藏的内容
  • 啊,我明白了,所以它基本上提取了模板化部分并将其公开,但将未模板化的任何内容隐藏起来。这是一项有趣的技术。
猜你喜欢
  • 2019-12-06
  • 1970-01-01
  • 1970-01-01
  • 2010-12-13
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多