C++ 将传递的参数限制为非临时字符串文字
因为我提出了以下解决方案:C++ 将传递的参数限制为非临时字符串文字,c++,c++11,c++14,C++,C++11,C++14,因为我提出了以下解决方案: #include <cstdlib> class Literal { public: template <std::size_t N> constexpr Literal(const char (&str)[N]) : mStr(str), mLength(checkForTrailingZeroAndGetLength(str[N - 1], N)) { } tem
#include <cstdlib>
class Literal
{
public:
template <std::size_t N> constexpr
Literal(const char (&str)[N])
: mStr(str),
mLength(checkForTrailingZeroAndGetLength(str[N - 1], N))
{
}
template <std::size_t N> Literal(char (&str)[N]) = delete;
constexpr operator const char*() const noexcept
{
return mStr;
}
constexpr const char* c_str() const noexcept
{
return mStr;
}
private:
const char* mStr;
std::size_t mLength;
struct Not_a_CString_Exception{};
constexpr static
std::size_t checkForTrailingZeroAndGetLength(char ch, std::size_t sz)
{
return (ch) ? throw Not_a_CString_Exception() : (sz - 1);
}
};
#包括
类文字
{
公众:
模板constexpr
文字(常量字符(&str)[N])
:mStr(str),
mLength(检查RailingZeroAndGetLength(str[N-1],N))
{
}
模板文字(char&str)[N])=delete;
constexpr运算符const char*()const noexcept
{
返回mStr;
}
constexpr const char*c_str()const noexcept
{
返回mStr;
}
私人:
常量字符*mStr;
标准:尺寸和长度;
结构不存在异常{};
constexpr静态
std::size\u t CheckforRailingZeroAndGetLength(字符通道,std::size\u t sz)
{
return(ch)?throw Not_a_CString_Exception():(sz-1);
}
};
它工作得很好,但是仍然可以使用自动存储持续时间从数组创建一个文本。我想在编译时阻止它。以下示例具有未定义的行为:
#include <cstdio>
static Literal okay()
{
static constexpr const char okay[] = "okay";
return { okay };
}
static Literal boom()
{
const char boom[] = "boom"; //Oops, static forgotten
return { boom }; // <= How to force a compile error here?
}
int main()
{
printf("%s\n", okay().c_str()); // <= the intended use case
printf("%s\n", boom().c_str()); // <= the undefined behaviour
return 0;
}
#包括
静态文本OK()
{
静态constexpr const char ok[]=“ok”;
返回{okay};
}
静态文字动臂()
{
const char boom[]=“boom”//Oops,静态遗忘
返回{boom}不,这是不可能的。好的
,繁荣
,以及相同大小的字符串文字都具有相同的类型,并且不能作为表达式区分。为什么不坚持文字运算符的方式呢实际上我们使用文字已经有一段时间了,从来没有遇到过这个陷阱,因为我们的开发人员通常采用另一方面,如果某个开发人员出于任何原因编写这样的构造,我更希望在编译时捕获它,而不是没完没了的调试会话。听起来你应该将适用的ctor设置为私有,并将文字运算符模板设置为好友。