【发布时间】: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;
main.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