将传递的参数限制为字符串文字 [英] Restrict passed parameter to a string literal

查看:118
本文介绍了将传递的参数限制为字符串文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类来包装字符串文字和计算编译时的大小。

I have a class to wrap string literals and calculate the size at compile time.

构造函数看起来像这样:

The constructor looks like this:

template< std::size_t N >
Literal( const char (&literal)[N] );

// used like this
Literal greet( "Hello World!" );
printf( "%s, length: %d", greet.c_str(), greet.size() );

但是代码有问题。下面的代码编译,我想让它一个错误。

There is problem with the code however. The following code compiles and I would like to make it an error.

char broke[] = { 'a', 'b', 'c' };
Literal l( broke );

有一种方法来限制构造函数,使其只接受c字符串文字?

Is there a way to restrict the constructor so that it only accepts c string literals? Compile time detection is preferred, but runtime is acceptable if there is no better way.

推荐答案

有一种强制使用字符串的方法字面量参数:创建一个用户定义的字面量操作符。您可以让运算符 constexpr 在编译时获取大小:

There is a way to force a string literal argument: make a user defined literal operator. You can make the operator constexpr to get the size at compile time:

constexpr Literal operator "" _suffix(char const* str, size_t len);
    return Literal(chars, len);
}



我不知道目前实现此功能的任何编译器。

I don't know of any compiler that implements this feature at this time.

这篇关于将传递的参数限制为字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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