【问题标题】:Concatenate string literals at compile time在编译时连接字符串文字
【发布时间】:2021-11-18 00:37:27
【问题描述】:

我需要将可变数量的字符串文字连接成一个以在 static_assert() 中使用它

我尝试使用带有结构的模板,但编译器不喜欢将文字作为模板参数。

error: the address of ‘m1’ is not a valid template argument because it does not have static storage duration.
error: ‘"thre"’ is not a valid template argument for type ‘const char*’ because string literals can never be used in this context

我也尝试过完美转发,但出现错误:‘args#0’ is not a constant expression

template<size_t size>
constexpr size_t const_strssize(const char (&)[size]) {
        return size;
}

template<class... Ts> 
constexpr size_t const_strssize(Ts&&... args) {
        return const_sum<(const_strssize(std::forward<const Ts>(args)), ...)>::get;
}

澄清一下,我不能做"string1" "string2",因为我从函数中得到的一些字符串返回了。

请不要推荐 strlen 或 memcpy 之类的东西。我知道,它们可以在编译时计算出来。

【问题讨论】:

  • C++20 NTTP可以做到这一点,你有更具体的例子吗?

标签: c++17 variadic-templates string-concatenation constexpr-function


【解决方案1】:

static_assert() 指定接受字符串文字。您可以编写的任何 constexpr 函数都可以返回一个常量,但不能返回字面量。所以你只能使用预处理器为static_assert 构造字符串。对不起。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-21
    • 2010-12-18
    • 1970-01-01
    • 2018-01-09
    相关资源
    最近更新 更多