C++11 作为模板参数的用户定义字符串文字的长度?

C++11 作为模板参数的用户定义字符串文字的长度?,c++11,generic-programming,user-defined-literals,C++11,Generic Programming,User Defined Literals,有没有办法让你有这样的行为 // Some definition(s) of operator "" _my_str // Some definition of function or macro MY_STR_LEN using T1 = MY_STR_LEN("ape"_my_str); // T1 is std::integral_constant<std::size_t, 3U>. using T2 = MY_STR_LEN(&qu

有没有办法让你有这样的行为

// Some definition(s) of operator "" _my_str
// Some definition of function or macro MY_STR_LEN

using T1 = MY_STR_LEN("ape"_my_str);
// T1 is std::integral_constant<std::size_t, 3U>.

using T2 = MY_STR_LEN("aardvark"_my_str);
// T2 is std::integral_constant<std::size_t, 8U>.

仔细阅读C++11 2.14.8可以发现,“文字运算符模板”仅用于数字文字,而不用于字符串和字符文字

但是,以下方法似乎为您提供了对字符串长度(但不是指针)的constexpr访问权限:

测试:

#包括
使用atype=std::array;//好啊

是的,但这只适用于一个特定对象
s
。所以我们需要为每个用户定义的文本指定一个名称?我也无法计算出
myTemplate运算符“”\u test(char const*s,unsigned int len)
。@MooingDuck:这是什么意思?正如我所说的,对于字符串文本,长度只能作为动态参数使用,而不能作为常量表达式使用,因此我认为不能在长度上参数化模板。。。
#include <cstdlib>
#include <type_traits>
#include <string_view>

struct cexpr_str {
    const char* ptr;
    std::size_t len;

    template <std::size_t Len>
    constexpr cexpr_str(const char (&str)[Len]) noexcept
    : ptr(str), len(Len) {}
};

// Essentially the same as
// std::literals::string_view_literals::operator""sv :
template <cexpr_str Str>
constexpr std::string_view operator "" _my_str () noexcept
{
     return std::string_view(Str.ptr, Str.len);
}

#define MY_STR_LEN(sv) \
  std::integral_constant<std::size_t, (sv).size()>
struct MyStr
{
    char const * str;
    unsigned int len;
    constexpr MyStr(char const * p, unsigned int n) : str(p), len(n) {}
};

constexpr MyStr operator "" _xyz (char const * s, unsigned int len)
{
    return MyStr(s, len);
}

constexpr auto s = "Hello"_xyz;
#include <array>

using atype = std::array<int, s.len>; // OK