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

Geo*_*ton 8 c++ string-concatenation

我正在尝试使用模板来创建type_info::name()发出const限定名称的函数的模拟.例如typeid(bool const).name(),"bool"但我想看"bool const".所以对于泛型类型我定义:

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.
Run Code Online (Sandbox Code Playgroud)

然后type_name<bool>::_"bool".对于非const类型,显然我可以为每种类型添加一个单独的定义,等等char const *const type_name<bool const>::_ = "bool const";.但是我想我会尝试使用部分特化和连接宏来在一行中派生任何类型的const限定名称const - 先前定义的资格名称.所以

#define CAT(A, B) A B

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

但后来type_name<bool const>::_给我error C2143: syntax error: missing ';' before 'string'line [1].我认为这type_name<bool>::_是一个在编译时已知的静态字符串,那么如何在编译时将其连接起来" const"呢?

我尝试了更简单的例子,但同样的问题:

char str1[4] = "int";
char *str2 = MYCAT(str1, " const");
Run Code Online (Sandbox Code Playgroud)

nit*_*oid 15

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.

#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';
}
Run Code Online (Sandbox Code Playgroud)

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.

Edited with improvements thanks to @Jarod42

  • @Fenixphoenix那是因为你无法将右值绑定到 ref 模板参数,你需要一个 constexpr 对象 (2认同)

nit*_*oid 5

编辑 - 在此处查看我的新的、改进的答案。


基于@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;
}
Run Code Online (Sandbox Code Playgroud)

我使用了 c++17 withstd::string_view因为该size方法很方便,但这可以const char[]像@Hedede 一样轻松地适应使用文字。

这个答案旨在作为对问题标题的回应,而不是描述的更小众的问题。