Pra*_*han 4 c++ templates crtp c++11
我试图使用CRTPed基地来保存一些静态初始化代码,如下所示:
template <typename T>
class InitCRTP
{
public:
static InitHelper<T> init;
};
template <typename T> InitHelper<T> InitCRTP<T>::init;
Run Code Online (Sandbox Code Playgroud)
现在,任何需要完成工作的类InitHelper<T>都可以这样做:
class WantInit : public InitCRTP<WantInit>
{
public:
void dummy(){init;}//To force instantiation of init
};
template class InitCRTP<WantInit>;//Forcing instantiation of init through explicit instantiation of `InitCRTP<WantInit>`.
Run Code Online (Sandbox Code Playgroud)
为了强制实例化InitCRTP<WantInit>::init,我可以使用dummy或使用如上所示的显式实例化.有没有办法解决这个问题,两者都没有?我希望这种模式的用户能够简单地继承InitCRTP<WantInit>而不用担心其他任何事情.如果它有帮助,使用C++11不是问题.
Joh*_*itb 10
您可以将变量作为参考模板参数传递.然后需要该对象导致实例化
template <typename T, T /*unnamed*/>
struct NonTypeParameter { };
template <typename T>
class InitCRTP
{
public:
static InitHelper init;
typedef NonTypeParameter<InitHelper&, init> object_user_dummy;
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
757 次 |
| 最近记录: |