简体   繁体   English

如何初始化参数化模板 class 的 static 成员

[英]How to initialize a static member of a parametrized-template class

I don't think my question is a duplicate of this one .我不认为我的问题是这个问题的重复。

what I try to do:我想做什么:

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'

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.这意味着 CReentranceLock 的所有实例都会有自己的 static,依赖于作为模板参数传递的 function 名称的 const char 地址。

and that could be used like this:可以这样使用:

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);
}

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.好吧,这只是理论......不幸的是,这在我尝试初始化静态的行中无法在 visual 2010 下编译。

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

what am I doing or thinking wrong?我在做什么或想错了什么?

PS: and I am not dealing with the fact that reentrance is smelling like an awful design (in MFC), I know, I am lost in the middle of it;-) PS:我并没有处理这样一个事实,即重新进入闻起来像一个糟糕的设计(在 MFC 中),我知道,我在其中迷路了;-)

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.编辑:虽然下面的答案很好,并且定义编译......我在CMyObject::InAnyFunction()中使用 const char * 作为编译时可用的模板参数似乎是错误的。 :-( :-(

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

This should be:这应该是:

bool CReentranceLock<szFunctionName>::s_bLock=false; 

Just change the line to只需将行更改为

bool CReentranceLock<szFunctionName>::s_bLock=false;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM