简体   繁体   English

如何在编译时连接静态字符串?

[英]How to concatenate static strings at compile time?

I am trying to use templates to create an analogue of the type_info::name() function which emits the const -qualified name.我正在尝试使用模板来创建发出const限定名称的type_info::name()函数的模拟。 Eg typeid(bool const).name() is "bool" but I want to see "bool const" .例如typeid(bool const).name()"bool"但我想看到"bool const" So for generic types I define:所以对于泛型我定义:

template<class T> struct type_name { static char const *const _; };

template<class T> char const *const type_name<T>::_ = "type unknown";

char const *const type_name<bool>::_ = "bool";
char const *const type_name<int>::_ = "int";
//etc.

Then type_name<bool>::_ is "bool" .然后type_name<bool>::_"bool" For non-const types obviously I could add a separate definition for each type, so char const *const type_name<bool const>::_ = "bool const";对于非常量类型,显然我可以为每种类型添加一个单独的定义,所以char const *const type_name<bool const>::_ = "bool const"; etc. But I thought I would try a partial specialization and a concatenation macro to derive in one line the const-qualified name for any type which has its non- const -qualified name previously defined.等等,但我想我会尝试一个部分特化和一个连接宏,以便在一行中为任何先前定义了非const限定名称的类型导出const限定名称。 So所以

#define CAT(A, B) A B

template<class T> char const *const type_name<T const>::_
    = CAT(type_name<T>::_, " const"); // line [1]

But then type_name<bool const>::_ gives me error C2143: syntax error: missing ';' before 'string'但是type_name<bool const>::_给了我error C2143: syntax error: missing ';' before 'string' error C2143: syntax error: missing ';' before 'string' for line [1] . error C2143: syntax error: missing ';' before 'string' line [1] error C2143: syntax error: missing ';' before 'string' I think that type_name<bool>::_ is a static string known at compile time, so how do I get it concatenated with " const" at compile time?我认为type_name<bool>::_是编译时已知的静态字符串,那么如何在编译时将它与" const"连接起来?

I tried more simple example but same problem:我尝试了更简单的例子,但同样的问题:

char str1[4] = "int";
char *str2 = MYCAT(str1, " const");

I recently revisited this problem, and found that the previous answer I gave produced ridiculously long compile times when concatenating more than a handful of strings.我最近重新审视了这个问题,发现我之前给出的答案在连接多个字符串时产生了非常长的编译时间。

I have produced a new solution which leverages constexpr functions to remove the recursive templates responsible for the long compilation time.我开发了一个新的解决方案,它利用 constexpr 函数来删除导致编译时间过长的递归模板。

#include <array>
#include <iostream>
#include <string_view>

template <std::string_view const&... Strs>
struct join
{
    // Join all strings into a single std::array of chars
    static constexpr auto impl() noexcept
    {
        constexpr std::size_t len = (Strs.size() + ... + 0);
        std::array<char, len + 1> arr{};
        auto append = [i = 0, &arr](auto const& s) mutable {
            for (auto c : s) arr[i++] = c;
        };
        (append(Strs), ...);
        arr[len] = 0;
        return arr;
    }
    // Give the joined string static storage
    static constexpr auto arr = impl();
    // View as a std::string_view
    static constexpr std::string_view value {arr.data(), arr.size() - 1};
};
// Helper to get the value out
template <std::string_view const&... Strs>
static constexpr auto join_v = join<Strs...>::value;

// Hello world example
static constexpr std::string_view hello = "hello";
static constexpr std::string_view space = " ";
static constexpr std::string_view world = "world";
static constexpr std::string_view bang = "!";
// Join them all together
static constexpr auto joined = join_v<hello, space, world, bang>;

int main()
{
    std::cout << joined << '\n';
}

This gives much quicker compile times, even with a large quantity of strings to concatenate.这提供了更快的编译时间,即使要连接大量字符串也是如此。

I personally find this solution easier to follow as the constexpr impl function is akin to how this could be solved at runtime.我个人觉得这个解决方案更容易遵循,因为constexpr impl函数类似于如何在运行时解决这个问题。

Edited with improvements thanks to @Jarod42与感谢改进编辑以@ Jarod42

EDIT - See my new, improved answer here.编辑 - 在此处查看我的新的、改进的答案。


Building on @Hededes answer , if we allow recursive templates, then concatenation of many strings can be implemented as:基于@Hededes answer ,如果我们允许递归模板,那么可以将多个字符串的串联实现为:

#include <string_view>
#include <utility>
#include <iostream>

namespace impl
{
/// Base declaration of our constexpr string_view concatenation helper
template <std::string_view const&, typename, std::string_view const&, typename>
struct concat;

/// Specialisation to yield indices for each char in both provided string_views,
/// allows us flatten them into a single char array
template <std::string_view const& S1,
          std::size_t... I1,
          std::string_view const& S2,
          std::size_t... I2>
struct concat<S1, std::index_sequence<I1...>, S2, std::index_sequence<I2...>>
{
  static constexpr const char value[]{S1[I1]..., S2[I2]..., 0};
};
} // namespace impl

/// Base definition for compile time joining of strings
template <std::string_view const&...> struct join;

/// When no strings are given, provide an empty literal
template <>
struct join<>
{
  static constexpr std::string_view value = "";
};

/// Base case for recursion where we reach a pair of strings, we concatenate
/// them to produce a new constexpr string
template <std::string_view const& S1, std::string_view const& S2>
struct join<S1, S2>
{
  static constexpr std::string_view value =
    impl::concat<S1,
                 std::make_index_sequence<S1.size()>,
                 S2,
                 std::make_index_sequence<S2.size()>>::value;
};

/// Main recursive definition for constexpr joining, pass the tail down to our
/// base case specialisation
template <std::string_view const& S, std::string_view const&... Rest>
struct join<S, Rest...>
{
  static constexpr std::string_view value =
    join<S, join<Rest...>::value>::value;
};

/// Join constexpr string_views to produce another constexpr string_view
template <std::string_view const&... Strs>
static constexpr auto join_v = join<Strs...>::value;


namespace str
{
static constexpr std::string_view a = "Hello ";
static constexpr std::string_view b = "world";
static constexpr std::string_view c = "!";
}

int main()
{
  constexpr auto joined = join_v<str::a, str::b, str::c>;
  std::cout << joined << '\n';
  return 0;
}

I used c++17 with std::string_view as the size method is handy, but this could easily be adapted to use const char[] literals as @Hedede did.我将 c++17 与std::string_view因为size方法很方便,但这可以很容易地适应使用const char[]文字,就像@Hedede 所做的那样。

This answer is intended as a response to the title of the question, rather than the more niche problem described.这个答案旨在作为对问题标题的回应,而不是描述的更小众的问题。

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

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