C PIMPL成语,类模板和void模板参数
C++ Pimpl idiom, class templates, and void template parameter
我正在尝试将PIMPL成语与类模板一起使用,并在模板参数为void
时遇到问题。这是我最新人为的例子:
#include <memory>
template<typename T> class Foo {
class Impl;
std::shared_ptr<Impl> pImpl;
public:
Foo()
: pImpl{new Impl()} {
}
void set(T value) {
pImpl->set(value);
}
T get() {
return pImpl->get();
}
};
template<typename T> class Foo<T>::Impl {
T value;
public:
void set(T value) {
this->value = value; // among other things
}
T get() {
return value; // among other things
}
};
template<> class Foo<void> {
class Impl;
std::shared_ptr<Impl> pImpl;
public:
void set() {
pImpl->set();
}
void get() {
pImpl->get();
}
};
class Foo<void>::Impl {
public:
void set() {
// do useful stuff
}
void get() {
// do useful stuff
}
};
在以下内容中编译上述结果:
$ g++ -dumpversion
4.8.5
void_int_template.cpp: In member function ‘void Foo<void>::set()’:
void_int_template.cpp:34:14: error: invalid use of incomplete type ‘class Foo<void>::Impl’
pImpl->set();
^
void_int_template.cpp:30:27: error: forward declaration of ‘class Foo<void>::Impl’
class Impl;
^
void_int_template.cpp: In member function ‘void Foo<void>::get()’:
void_int_template.cpp:37:14: error: invalid use of incomplete type ‘class Foo<void>::Impl’
pImpl->get();
^
void_int_template.cpp:30:27: error: forward declaration of ‘class Foo<void>::Impl’
class Impl;
^
我如何专业化类模板来容纳void
模板参数?
完整的专业化提供了替代定义,这意味着您必须重新定义所有内容。
template<> class Foo<void> {
class Impl;
std::shared_ptr<Impl> pImpl;
public:
Foo();
void set();
void get();
};
class Foo<void>::Impl {
public:
void set() {
}
void get() {
}
};
// these need to be inline iff it's in your header file
/* inline */ Foo<void>::Foo() : pImpl(new Impl) {}
/* inline */ void Foo<void>::set() { pImpl->set(); }
/* inline */ void Foo<void>::get() { pImpl->get(); }
相关文章:
- 在派生函数中指定void*参数
- void 函数可以传递值参数吗?
- 如何在C++中使用 Void 而不会收到有关参数的错误
- std::function<void()> 接受参数
- C++ 类型的参数与 void (__cdecl*)(void) 类型的参数不兼容,当调用 std::atexit()
- 是否将invoke_result与void参数类型一起使用
- 组合模板参数形成函数签名时无效的 void 参数
- 使用void* 参数定义纯虚函数的抽象基类.派生类匹配参数是指向某种类型的指针
- 为什么 void 参数不能存在于具有多个参数的函数中?
- Pthreads将void*参数强制转换为int数组
- C 函数声明对类型"void(*fcn)(void*)"参数的说明
- 从模拟函数调用中捕获 void* 参数
- 为void参数指定一个模板
- 如何在c++ OCX模块中指定一个接受void*参数的函数
- 某些 GL 函数的好奇"void*"参数
- 如何在C++中为多个对象类型使用void*参数
- 如何使void*参数在函数中保存其局部结果,该函数使用struct *调用
- 在需要void*参数的函数中传递unique_ptr最安全的方法是什么?
- 如何在类/函数模板中传递void参数
- 没有参数和C++中的void参数有什么区别