简体   繁体   English

使用const char *(nullptr)进行编译时检查

[英]compile-time check with const char* (nullptr)

I have a template class that takes a string literal as parameter. 我有一个模板类,它使用字符串文字作为参数。 The code works fine - but I've got one question, whether it is possible to use compile-time check to skip the generating of if (S) or else block body at all? 该代码工作正常-但我有一个问题,是否可以使用编译时检查跳过的发生if (S)else块体呢? (Something like the __if_exists or #if, traits, etc). (类似于__if_exists或#if,特征等)。 I understand that I could have a specialized A<nullptr> that defines a different print() function, but also want to know whether there's other (more simple) ways of doing this. 我知道我可以有一个专门的A<nullptr>来定义一个不同的print()函数,但是还想知道是否还有其他(更简单的)方法可以做到这一点。 Thanks! 谢谢!

template<char const* S = nullptr>
class A
{
public:
    void print()
    {
        if (S)
            cout << S << endl;
        else
            cout << "nullptr" << endl;
    }
};

In your case, can't you set the default value of S as "nullptr" or any other constant string? 在您的情况下,不能将S的默认值设置为“ nullptr”或任何其他常量字符串吗? Of course, this works when you don't actually need S to be NULL, but it will skip the if check. 当然,当您实际上不需要S为NULL时,此方法有效,但是它将跳过if检查。

add a function, 添加一个功能,

constexpr const char* getStr(){
   return S? S : "null";
}

then it becomes, 然后变成

void print(){
   std::cout << getStr() << std::endl;
}

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

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