如何初始化参数化模板类的静态成员 [英] How to initialize a static member of a parametrized-template class

查看:36
本文介绍了如何初始化参数化模板类的静态成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不认为我的问题与这个问题重复.

我尝试做的事情:

template<const char* szFunctionName>
class CReentranceLock
{
public:
    CReentranceLock(){}
    ~CReentranceLock(){}
    bool isLocked(){return s_bLock;}
    void setLocked(bool b)
    {
        const bool Result=(bool)InterlockedCompareExchange(
                    (unsigned long *)&s_bLock, b, !b);
    }

private:
    static bool s_bLock;
};

template<const char* szFunctionName>
bool CReentranceLock<const char*szFunctionName>::s_bLock=false; 
// error C2146: syntax error : missing ',' before identifier 'szFunctionName'

暗示所有 CReentranceLock 实例都有自己的静态,依赖于作为模板参数传递的函数名称的 const char 地址.

implying that all instances of CReentranceLock would have their own static, relying on the const char address of the function name passed as a parameter of the template.

可以这样使用:

void CMyObject::InAnyFunction()
{
    const char* szFunctionName = __FUNCTION__; 
    CReentranceLock<szFunctionName> lock; // Edit: <- this doesn't work
    if(lock.isLocked()) return;
    lock.setLocked(true);
    /// business code
   lock.setLocked(false);
}

好吧,这只是理论...不幸的是,这不能在 Visual 2010 下编译,在我尝试初始化静态的那一行.

well that's only the theory... and unfortunately this doesn't compile under visual 2010, at the line where I try to initialize the statics.

error C2146: syntax error : missing ',' before identifier 'szFunctionName'

我在做什么或想错了什么?

what am I doing or thinking wrong ?

PS:而且我没有处理重入闻起来像一个可怕的设计(在 MFC 中)这一事实,我知道,我迷失在其中 ;-)

PS: and I am not dealing with the fact that reentrance is smelling like an awfull design (in MFC), I know, I am lost in the middle of it ;-)

编辑:虽然下面的答案很好,并且定义编译......我在 CMyObject::InAnyFunction() 中使用 const char * 作为编译时可用的模板参数似乎错了.:-(

Edit: though the answer below is good, and the definition compiles... my use in CMyObject::InAnyFunction() with a const char * as a template-parameter available at compile time seems to be wrong. :-(

推荐答案

bool CReentranceLock<const char*szFunctionName>::s_bLock=false; 

这应该是:

bool CReentranceLock<szFunctionName>::s_bLock=false; 

这篇关于如何初始化参数化模板类的静态成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆