C ++에서 컴파일 타임 문자열을 편리하게 선언
C ++에서 컴파일 타임에 문자열을 생성하고 조작 할 수 있다는 것은 몇 가지 유용한 응용 프로그램이 있습니다. C ++에서 컴파일 타임 문자열을 생성 할 수 있지만 문자열이 가변적 인 일련의 문자로 선언되어야하므로 프로세스가 매우 번거 롭습니다.
using str = sequence<'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!'>;
문자열 연결, 하위 문자열 추출 등의 작업은 일련의 문자에 대한 작업으로 쉽게 구현할 수 있습니다. 컴파일 타임 문자열을 더 편리하게 선언 할 수 있습니까? 그렇지 않은 경우, 컴파일 타임 문자열을 편리하게 선언 할 수있는 제안이 작품에 있습니까?
기존 접근 방식이 실패하는 이유
이상적으로는 컴파일 타임 문자열을 다음과 같이 선언 할 수 있습니다.
// Approach 1
using str1 = sequence<"Hello, world!">;
또는 사용자 정의 리터럴을 사용하여
// Approach 2
constexpr auto str2 = "Hello, world!"_s;
생성자 decltype(str2)
가있는 곳 constexpr
. 다음과 같은 작업을 수행 할 수 있다는 점을 활용하여 더 복잡한 버전의 접근 방식 1을 구현할 수 있습니다.
template <unsigned Size, const char Array[Size]>
struct foo;
그러나 배열에는 외부 연결이 필요하므로 접근법 1이 작동하려면 다음과 같이 작성해야합니다.
/* Implementation of array to sequence goes here. */
constexpr const char str[] = "Hello, world!";
int main()
{
using s = string<13, str>;
return 0;
}
말할 것도없이, 이것은 매우 불편합니다. 접근법 2는 실제로 구현할 수 없습니다. ( constexpr
) 리터럴 연산자 를 선언하려면 어떻게 반환 유형을 지정합니까? 연산자는 가변 문자 시퀀스를 반환해야하므로 const char*
매개 변수를 사용하여 반환 유형을 지정해야합니다.
constexpr auto
operator"" _s(const char* s, size_t n) -> /* Some metafunction using `s` */
이 아니기 때문에 컴파일 오류가 발생 s
합니다 constexpr
. 다음을 수행하여이 문제를 해결하려고 시도해도 큰 도움이되지 않습니다.
template <char... Ts>
constexpr sequence<Ts...> operator"" _s() { return {}; }
표준에 따르면이 특정 리터럴 연산자 양식은 정수 및 부동 소수점 유형으로 예약되어 있습니다. 123_s
작동 하지만 작동 abc_s
하지 않습니다. 사용자 정의 리터럴을 모두 버리고 정규 constexpr
함수를 사용하면 어떨까요?
template <unsigned Size>
constexpr auto
string(const char (&array)[Size]) -> /* Some metafunction using `array` */
이전과 마찬가지로 constexpr
함수 의 매개 변수 인 배열 자체가 더 이상 constexpr
유형 이 아니라는 문제가 발생합니다 .
문자열과 문자열의 크기를 인수로 사용하고 문자열의 문자로 구성된 시퀀스 (, 문자열 BOOST_PP_FOR
화, 배열 첨자 등)를 반환하는 C 전 처리기 매크로를 정의하는 것이 가능해야한다고 생각합니다 . 그러나, 나는 그러한 매크로를 구현할 시간 (또는 충분한 관심)이 없습니다 =)
나는 C ++ Now 2012 에서 발표 된 Scott Schurr의str_const
우아함과 어울리는 것을 보지 못했습니다 . 그래도 필요합니다 .constexpr
사용 방법과 수행 할 수있는 작업은 다음과 같습니다.
int
main()
{
constexpr str_const my_string = "Hello, world!";
static_assert(my_string.size() == 13, "");
static_assert(my_string[4] == 'o', "");
constexpr str_const my_other_string = my_string;
static_assert(my_string == my_other_string, "");
constexpr str_const world(my_string, 7, 5);
static_assert(world == "world", "");
// constexpr char x = world[5]; // Does not compile because index is out of range!
}
컴파일 타임 범위 검사보다 훨씬 시원하지 않습니다!
사용과 구현 모두 매크로가 없습니다. 그리고 문자열 크기에는 인위적인 제한이 없습니다. 구현을 여기에 게시하지만 Scott의 암시 적 저작권을 존중합니다. 구현은 위에 링크 된 프레젠테이션의 단일 슬라이드에 있습니다.
문자열과 문자열의 크기를 인수로 사용하고 문자열의 문자로 구성된 시퀀스 (BOOST_PP_FOR, 문자열 화, 배열 첨자 등 사용)를 반환하는 C 전 처리기 매크로를 정의하는 것이 가능해야한다고 생각합니다. 그러나 그러한 매크로를 구현할 시간이 충분하지 않습니다.
매우 간단한 매크로와 일부 C ++ 11 기능을 사용하여 부스트에 의존하지 않고 이것을 구현할 수 있습니다.
- 람다
- 템플릿
- 일반화 된 상수 표현식
- 비 정적 데이터 멤버 이니셜 라이저
- 균일 한 초기화
(후자의 2 개는 여기서 엄격하게 요구되지는 않습니다)
우리는 사용자가 제공 한 인덱스를 0에서 N까지의 variadic 템플릿으로 인스턴스화 할 수 있어야합니다. 예를 들어 튜플을 variadic 템플릿 함수의 인수로 확장하는 데 유용한 도구도 있습니다 (질문 : 튜플을 variadic 템플릿 함수의 인수로 확장하는 방법은 무엇입니까?
" "튜플을 풀고하는 것은 일치하는 함수 포인터 호출 )namespace variadic_toolbox { template<unsigned count, template<unsigned...> class meta_functor, unsigned... indices> struct apply_range { typedef typename apply_range<count-1, meta_functor, count-1, indices...>::result result; }; template<template<unsigned...> class meta_functor, unsigned... indices> struct apply_range<0, meta_functor, indices...> { typedef typename meta_functor<indices...>::result result; }; }
그런 다음 유형이 아닌 매개 변수 char을 사용하여 string이라는 가변 템플릿을 정의하십시오.
namespace compile_time { template<char... str> struct string { static constexpr const char chars[sizeof...(str)+1] = {str..., '\0'}; }; template<char... str> constexpr const char string<str...>::chars[sizeof...(str)+1]; }
이제 가장 흥미로운 부분-문자 리터럴을 문자열 템플릿으로 전달하는 것입니다.
namespace compile_time { template<typename lambda_str_type> struct string_builder { template<unsigned... indices> struct produce { typedef string<lambda_str_type{}.chars[indices]...> result; }; }; } #define CSTRING(string_literal) \ []{ \ struct constexpr_string_type { const char * chars = string_literal; }; \ return variadic_toolbox::apply_range<sizeof(string_literal)-1, \ compile_time::string_builder<constexpr_string_type>::produce>::result{}; \ }()
간단한 연결 데모는 사용법을 보여줍니다.
namespace compile_time
{
template<char... str0, char... str1>
string<str0..., str1...> operator*(string<str0...>, string<str1...>)
{
return {};
}
}
int main()
{
auto str0 = CSTRING("hello");
auto str1 = CSTRING(" world");
std::cout << "runtime concat: " << str_hello.chars << str_world.chars << "\n <=> \n";
std::cout << "compile concat: " << (str_hello * str_world).chars << std::endl;
}
편집 : Howard Hinnant (및 OP에 대한 의견으로는 다소)에서 지적했듯이 문자열의 모든 단일 문자를 단일 템플릿 인수로 사용하는 유형이 필요하지 않을 수 있습니다. 필요한 경우 아래에 매크로없는 솔루션이 있습니다.
컴파일 타임에 문자열 작업을 시도하는 동안 발견 한 트릭이 있습니다. "템플릿 문자열"외에 다른 유형을 도입해야하지만 함수 내에서이 유형의 범위를 제한 할 수 있습니다.
매크로를 사용하지 않고 일부 C ++ 11 기능을 사용합니다.
#include <iostream>
// helper function
constexpr unsigned c_strlen( char const* str, unsigned count = 0 )
{
return ('\0' == str[0]) ? count : c_strlen(str+1, count+1);
}
// helper "function" struct
template < char t_c, char... tt_c >
struct rec_print
{
static void print()
{
std::cout << t_c;
rec_print < tt_c... > :: print ();
}
};
template < char t_c >
struct rec_print < t_c >
{
static void print() { std::cout << t_c; }
};
// destination "template string" type
template < char... tt_c >
struct exploded_string
{
static void print()
{
rec_print < tt_c... > :: print();
}
};
// struct to explode a `char const*` to an `exploded_string` type
template < typename T_StrProvider, unsigned t_len, char... tt_c >
struct explode_impl
{
using result =
typename explode_impl < T_StrProvider, t_len-1,
T_StrProvider::str()[t_len-1],
tt_c... > :: result;
};
template < typename T_StrProvider, char... tt_c >
struct explode_impl < T_StrProvider, 0, tt_c... >
{
using result = exploded_string < tt_c... >;
};
// syntactical sugar
template < typename T_StrProvider >
using explode =
typename explode_impl < T_StrProvider,
c_strlen(T_StrProvider::str()) > :: result;
int main()
{
// the trick is to introduce a type which provides the string, rather than
// storing the string itself
struct my_str_provider
{
constexpr static char const* str() { return "hello world"; }
};
auto my_str = explode < my_str_provider >{}; // as a variable
using My_Str = explode < my_str_provider >; // as a type
my_str.print();
}
Boost 솔루션 을 사용하지 않으려면 유사한 매크로를 만들 수 있습니다.
#define MACRO_GET_1(str, i) \
(sizeof(str) > (i) ? str[(i)] : 0)
#define MACRO_GET_4(str, i) \
MACRO_GET_1(str, i+0), \
MACRO_GET_1(str, i+1), \
MACRO_GET_1(str, i+2), \
MACRO_GET_1(str, i+3)
#define MACRO_GET_16(str, i) \
MACRO_GET_4(str, i+0), \
MACRO_GET_4(str, i+4), \
MACRO_GET_4(str, i+8), \
MACRO_GET_4(str, i+12)
#define MACRO_GET_64(str, i) \
MACRO_GET_16(str, i+0), \
MACRO_GET_16(str, i+16), \
MACRO_GET_16(str, i+32), \
MACRO_GET_16(str, i+48)
#define MACRO_GET_STR(str) MACRO_GET_64(str, 0), 0 //guard for longer strings
using seq = sequence<MACRO_GET_STR("Hello world!")>;
유일한 문제는 고정 된 64 자 (추가 0)입니다. 그러나 필요에 따라 쉽게 변경할 수 있습니다.
문자열과 문자열 크기를 인수로 사용하고 문자열의 문자로 구성된 시퀀스를 반환하는 C 전 처리기 매크로를 정의 할 수 있어야한다고 생각합니다 (BOOST_PP_FOR, 문자열 화, 배열 첨자 등 사용).
기사 : Abel Sinkovics와 Dave Abrahams의 C ++ 템플릿 메타 프로그램에서 문자열 사용 .
매크로 + BOOST_PP_REPEAT 사용에 대한 아이디어가 약간 개선되었습니다 . 매크로에 명시적인 크기를 전달할 필요가 없습니다. 즉, 문자열 크기 및 "문자열 오버런 방지"에 대한 고정 된 상한을 기반으로합니다.
template <int N>
constexpr char at(char const(&s)[N], int i)
{
return i >= N ? '\0' : s[i];
}
플러스 조건부 부스트 :: mpl :: push_back .
이 특정 문제를 해결하고 constexpr 또는 복잡한 전 처리기 코드를 사용하지 않고 우아하게 처리하기 때문에 Yankes의 솔루션으로 허용되는 답변을 변경했습니다.
후행 0, 손으로 쓴 매크로 반복, 확장 된 매크로에서 문자열의 2 배 반복을 수락 하고 Boost가없는 경우 동의합니다. 그러나 Boost를 사용하면 세 줄이됩니다.
#include <boost/preprocessor/repetition/repeat.hpp>
#define GET_STR_AUX(_, i, str) (sizeof(str) > (i) ? str[(i)] : 0),
#define GET_STR(str) BOOST_PP_REPEAT(64,GET_STR_AUX,str) 0
동료가 컴파일 타임에 메모리에 문자열을 연결하도록 요청했습니다. 컴파일 타임에 개별 문자열을 인스턴스화하는 것도 포함됩니다. 전체 코드 목록은 다음과 같습니다.
//Arrange strings contiguously in memory at compile-time from string literals.
//All free functions prefixed with "my" to faciliate grepping the symbol tree
//(none of them should show up).
#include <iostream>
using std::size_t;
//wrapper for const char* to "allocate" space for it at compile-time
template<size_t N>
struct String {
//C arrays can only be initialised with a comma-delimited list
//of values in curly braces. Good thing the compiler expands
//parameter packs into comma-delimited lists. Now we just have
//to get a parameter pack of char into the constructor.
template<typename... Args>
constexpr String(Args... args):_str{ args... } { }
const char _str[N];
};
//takes variadic number of chars, creates String object from it.
//i.e. myMakeStringFromChars('f', 'o', 'o', '\0') -> String<4>::_str = "foo"
template<typename... Args>
constexpr auto myMakeStringFromChars(Args... args) -> String<sizeof...(Args)> {
return String<sizeof...(args)>(args...);
}
//This struct is here just because the iteration is going up instead of
//down. The solution was to mix traditional template metaprogramming
//with constexpr to be able to terminate the recursion since the template
//parameter N is needed in order to return the right-sized String<N>.
//This class exists only to dispatch on the recursion being finished or not.
//The default below continues recursion.
template<bool TERMINATE>
struct RecurseOrStop {
template<size_t N, size_t I, typename... Args>
static constexpr String<N> recurseOrStop(const char* str, Args... args);
};
//Specialisation to terminate recursion when all characters have been
//stripped from the string and converted to a variadic template parameter pack.
template<>
struct RecurseOrStop<true> {
template<size_t N, size_t I, typename... Args>
static constexpr String<N> recurseOrStop(const char* str, Args... args);
};
//Actual function to recurse over the string and turn it into a variadic
//parameter list of characters.
//Named differently to avoid infinite recursion.
template<size_t N, size_t I = 0, typename... Args>
constexpr String<N> myRecurseOrStop(const char* str, Args... args) {
//template needed after :: since the compiler needs to distinguish
//between recurseOrStop being a function template with 2 paramaters
//or an enum being compared to N (recurseOrStop < N)
return RecurseOrStop<I == N>::template recurseOrStop<N, I>(str, args...);
}
//implementation of the declaration above
//add a character to the end of the parameter pack and recurse to next character.
template<bool TERMINATE>
template<size_t N, size_t I, typename... Args>
constexpr String<N> RecurseOrStop<TERMINATE>::recurseOrStop(const char* str,
Args... args) {
return myRecurseOrStop<N, I + 1>(str, args..., str[I]);
}
//implementation of the declaration above
//terminate recursion and construct string from full list of characters.
template<size_t N, size_t I, typename... Args>
constexpr String<N> RecurseOrStop<true>::recurseOrStop(const char* str,
Args... args) {
return myMakeStringFromChars(args...);
}
//takes a compile-time static string literal and returns String<N> from it
//this happens by transforming the string literal into a variadic paramater
//pack of char.
//i.e. myMakeString("foo") -> calls myMakeStringFromChars('f', 'o', 'o', '\0');
template<size_t N>
constexpr String<N> myMakeString(const char (&str)[N]) {
return myRecurseOrStop<N>(str);
}
//Simple tuple implementation. The only reason std::tuple isn't being used
//is because its only constexpr constructor is the default constructor.
//We need a constexpr constructor to be able to do compile-time shenanigans,
//and it's easier to roll our own tuple than to edit the standard library code.
//use MyTupleLeaf to construct MyTuple and make sure the order in memory
//is the same as the order of the variadic parameter pack passed to MyTuple.
template<typename T>
struct MyTupleLeaf {
constexpr MyTupleLeaf(T value):_value(value) { }
T _value;
};
//Use MyTupleLeaf implementation to define MyTuple.
//Won't work if used with 2 String<> objects of the same size but this
//is just a toy implementation anyway. Multiple inheritance guarantees
//data in the same order in memory as the variadic parameters.
template<typename... Args>
struct MyTuple: public MyTupleLeaf<Args>... {
constexpr MyTuple(Args... args):MyTupleLeaf<Args>(args)... { }
};
//Helper function akin to std::make_tuple. Needed since functions can deduce
//types from parameter values, but classes can't.
template<typename... Args>
constexpr MyTuple<Args...> myMakeTuple(Args... args) {
return MyTuple<Args...>(args...);
}
//Takes a variadic list of string literals and returns a tuple of String<> objects.
//These will be contiguous in memory. Trailing '\0' adds 1 to the size of each string.
//i.e. ("foo", "foobar") -> (const char (&arg1)[4], const char (&arg2)[7]) params ->
// -> MyTuple<String<4>, String<7>> return value
template<size_t... Sizes>
constexpr auto myMakeStrings(const char (&...args)[Sizes]) -> MyTuple<String<Sizes>...> {
//expands into myMakeTuple(myMakeString(arg1), myMakeString(arg2), ...)
return myMakeTuple(myMakeString(args)...);
}
//Prints tuple of strings
template<typename T> //just to avoid typing the tuple type of the strings param
void printStrings(const T& strings) {
//No std::get or any other helpers for MyTuple, so intead just cast it to
//const char* to explore its layout in memory. We could add iterators to
//myTuple and do "for(auto data: strings)" for ease of use, but the whole
//point of this exercise is the memory layout and nothing makes that clearer
//than the ugly cast below.
const char* const chars = reinterpret_cast<const char*>(&strings);
std::cout << "Printing strings of total size " << sizeof(strings);
std::cout << " bytes:\n";
std::cout << "-------------------------------\n";
for(size_t i = 0; i < sizeof(strings); ++i) {
chars[i] == '\0' ? std::cout << "\n" : std::cout << chars[i];
}
std::cout << "-------------------------------\n";
std::cout << "\n\n";
}
int main() {
{
constexpr auto strings = myMakeStrings("foo", "foobar",
"strings at compile time");
printStrings(strings);
}
{
constexpr auto strings = myMakeStrings("Some more strings",
"just to show Jeff to not try",
"to challenge C++11 again :P",
"with more",
"to show this is variadic");
printStrings(strings);
}
std::cout << "Running 'objdump -t |grep my' should show that none of the\n";
std::cout << "functions defined in this file (except printStrings()) are in\n";
std::cout << "the executable. All computations are done by the compiler at\n";
std::cout << "compile-time. printStrings() executes at run-time.\n";
}
다음은 전달 된 각 컴파일 타임 문자열에 대해 std :: tuple <char ...>을 만드는 간결한 C ++ 14 솔루션입니다.
#include <tuple>
#include <utility>
namespace detail {
template <std::size_t ... indices>
decltype(auto) build_string(const char * str, std::index_sequence<indices...>) {
return std::make_tuple(str[indices]...);
}
}
template <std::size_t N>
constexpr decltype(auto) make_string(const char(&str)[N]) {
return detail::build_string(str, std::make_index_sequence<N>());
}
auto HelloStrObject = make_string("hello");
그리고 여기에 다른 매크로 포스트에서 손질 된 고유 한 컴파일 타임 유형을 만드는 방법이 있습니다.
#include <utility>
template <char ... Chars>
struct String {};
template <typename Str, std::size_t ... indices>
decltype(auto) build_string(std::index_sequence<indices...>) {
return String<Str().chars[indices]...>();
}
#define make_string(str) []{\
struct Str { const char * chars = str; };\
return build_string<Str>(std::make_index_sequence<sizeof(str)>());\
}()
auto HelloStrObject = make_string("hello");
사용자 정의 리터럴을 아직 사용할 수 없다는 것이 너무 나쁩니다.
Howard Hinnant의 아이디어를 기반으로 두 리터럴을 함께 추가하는 리터럴 클래스를 만들 수 있습니다.
template<int>
using charDummy = char;
template<int... dummy>
struct F
{
const char table[sizeof...(dummy) + 1];
constexpr F(const char* a) : table{ str_at<dummy>(a)..., 0}
{
}
constexpr F(charDummy<dummy>... a) : table{ a..., 0}
{
}
constexpr F(const F& a) : table{ a.table[dummy]..., 0}
{
}
template<int... dummyB>
constexpr F<dummy..., sizeof...(dummy)+dummyB...> operator+(F<dummyB...> b)
{
return { this->table[dummy]..., b.table[dummyB]... };
}
};
template<int I>
struct get_string
{
constexpr static auto g(const char* a) -> decltype( get_string<I-1>::g(a) + F<0>(a + I))
{
return get_string<I-1>::g(a) + F<0>(a + I);
}
};
template<>
struct get_string<0>
{
constexpr static F<0> g(const char* a)
{
return {a};
}
};
template<int I>
constexpr auto make_string(const char (&a)[I]) -> decltype( get_string<I-2>::g(a) )
{
return get_string<I-2>::g(a);
}
constexpr auto a = make_string("abc");
constexpr auto b = a+ make_string("def"); // b.table == "abcdef"
아무도 내 다른 대답을 좋아하지 않는 것 같습니다 :-<. 그래서 여기 str_const를 실제 타입으로 변환하는 방법을 보여줍니다 :
#include <iostream>
#include <utility>
// constexpr string with const member functions
class str_const {
private:
const char* const p_;
const std::size_t sz_;
public:
template<std::size_t N>
constexpr str_const(const char(&a)[N]) : // ctor
p_(a), sz_(N-1) {}
constexpr char operator[](std::size_t n) const {
return n < sz_ ? p_[n] :
throw std::out_of_range("");
}
constexpr std::size_t size() const { return sz_; } // size()
};
template <char... letters>
struct string_t{
static char const * c_str() {
static constexpr char string[]={letters...,'\0'};
return string;
}
};
template<str_const const& str,std::size_t... I>
auto constexpr expand(std::index_sequence<I...>){
return string_t<str[I]...>{};
}
template<str_const const& str>
using string_const_to_type = decltype(expand<str>(std::make_index_sequence<str.size()>{}));
constexpr str_const hello{"Hello World"};
using hello_t = string_const_to_type<hello>;
int main()
{
// char c = hello_t{}; // Compile error to print type
std::cout << hello_t::c_str();
return 0;
}
clang ++ -stdlib = libc ++ -std = c ++ 14 (clang 3.7)로 컴파일
고유 한 컴파일 타임 유형을 생성하기위한 kacey의 솔루션은 약간만 수정하면 C ++ 11에서도 사용할 수 있습니다.
template <char... Chars>
struct string_t {};
namespace detail {
template <typename Str,unsigned int N,char... Chars>
struct make_string_t : make_string_t<Str,N-1,Str().chars[N-1],Chars...> {};
template <typename Str,char... Chars>
struct make_string_t<Str,0,Chars...> { typedef string_t<Chars...> type; };
} // namespace detail
#define CSTR(str) []{ \
struct Str { const char *chars = str; }; \
return detail::make_string_t<Str,sizeof(str)>::type(); \
}()
사용하다:
template <typename String>
void test(String) {
// ... String = string_t<'H','e','l','l','o','\0'>
}
test(CSTR("Hello"));
부스트 하나 맵을 가지고 놀면서 나는이 스레드를 발견했습니다. 답변 중 하나가 내 문제를 해결하지 못했을 때 잠재적으로 다른 사람들에게 도움이 될 수 있으므로 여기에 추가하려는 다른 솔루션을 찾았습니다.
내 문제는 hana 문자열과 함께 boost hana 맵을 사용할 때 컴파일러가 여전히 일부 런타임 코드를 생성한다는 것입니다 (아래 참조). 그 이유는 컴파일 타임에 맵을 쿼리하려면 반드시 맵이어야하기 때문 constexpr
입니다. 애즈이 불가능 BOOST_HANA_STRING
매크로 사용할 수 없습니다 람다 생성 constexpr
컨텍스트. 반면에, 맵은 내용이 다른 문자열이 다른 유형이어야합니다.
이 스레드의 솔루션이 람다를 사용하거나 다른 내용에 대해 다른 유형을 제공하지 않으므로 다음 방법이 도움이됩니다. 또한 해키 str<'a', 'b', 'c'>
구문을 피 합니다.
기본 아이디어는 str_const
캐릭터의 해시에 템플릿 화 된 Scott Schurr의 버전을 갖는 것입니다 . 그것이 c++14
있지만 c++11
의 재귀 구현 가능해야 crc32
함수 (참조 여기 ).
// str_const from https://github.com/boostcon/cppnow_presentations_2012/blob/master/wed/schurr_cpp11_tools_for_class_authors.pdf?raw=true
#include <string>
template<unsigned Hash> ////// <- This is the difference...
class str_const2 { // constexpr string
private:
const char* const p_;
const std::size_t sz_;
public:
template<std::size_t N>
constexpr str_const2(const char(&a)[N]) : // ctor
p_(a), sz_(N - 1) {}
constexpr char operator[](std::size_t n) const { // []
return n < sz_ ? p_[n] :
throw std::out_of_range("");
}
constexpr std::size_t size() const { return sz_; } // size()
constexpr const char* const data() const {
return p_;
}
};
// Crc32 hash function. Non-recursive version of https://stackoverflow.com/a/23683218/8494588
static constexpr unsigned int crc_table[256] = {
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
};
template<size_t N>
constexpr auto crc32(const char(&str)[N])
{
unsigned int prev_crc = 0xFFFFFFFF;
for (auto idx = 0; idx < sizeof(str) - 1; ++idx)
prev_crc = (prev_crc >> 8) ^ crc_table[(prev_crc ^ str[idx]) & 0xFF];
return prev_crc ^ 0xFFFFFFFF;
}
// Conveniently create a str_const2
#define CSTRING(text) str_const2 < crc32( text ) >( text )
// Conveniently create a hana type_c<str_const2> for use in map
#define CSTRING_TYPE(text) hana::type_c<decltype(str_const2 < crc32( text ) >( text ))>
용법:
#include <boost/hana.hpp>
#include <boost/hana/map.hpp>
#include <boost/hana/pair.hpp>
#include <boost/hana/type.hpp>
namespace hana = boost::hana;
int main() {
constexpr auto s2 = CSTRING("blah");
constexpr auto X = hana::make_map(
hana::make_pair(CSTRING_TYPE("aa"), 1)
);
constexpr auto X2 = hana::insert(X, hana::make_pair(CSTRING_TYPE("aab"), 2));
constexpr auto ret = X2[(CSTRING_TYPE("aab"))];
return ret;
}
clang-cl
5.0의 결과 어셈블러 코드 는 다음 과 같습니다.
012A1370 mov eax,2
012A1375 ret
당신의 접근법 # 1이 맞습니다.
그러나 배열에는 외부 연결이 필요하므로 접근 방식 1이 작동하려면 다음과 같이 작성해야합니다. constexpr const char str [] = "Hello, world!";
아니요, 정확하지 않습니다. 이것은 clang과 gcc로 컴파일됩니다. 나는 표준 C ++ 11을 희망하지만 언어가 아닙니다.
#include <iostream>
template <char... letters>
struct string_t{
static char const * c_str() {
static constexpr char string[]={letters...,'\0'};
return string;
}
};
// just live with it, but only once
using Hello_World_t = string_t<'H','e','l','l','o',' ','w','o','r','l','d','!'>;
template <typename Name>
void print()
{
//String as template parameter
std::cout << Name::c_str();
}
int main() {
std::cout << Hello_World_t::c_str() << std::endl;
print<Hello_World_t>();
return 0;
}
c ++ 17에서 내가 정말로 좋아하는 것은 다음과 같습니다 (접근법 # 1 완료).
// for template <char...>
<"Text"> == <'T','e','x','t'>
void-pointer가 언급했듯이 숫자에 대해서만 템플릿 사용자 정의 리터럴의 표준에 매우 유사한 것이 이미 존재합니다. 그때까지 다른 작은 트릭은 재정의 편집 모드 + 복사하여 붙여 넣기를 사용하는 것입니다.
string_t<' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '>;
매크로가 마음에 들지 않으면이 방법보다 작동합니다 (Yankes 답변에서 약간 수정 됨).
#define MACRO_GET_1(str, i) \
(sizeof(str) > (i) ? str[(i)] : 0)
#define MACRO_GET_4(str, i) \
MACRO_GET_1(str, i+0), \
MACRO_GET_1(str, i+1), \
MACRO_GET_1(str, i+2), \
MACRO_GET_1(str, i+3)
#define MACRO_GET_16(str, i) \
MACRO_GET_4(str, i+0), \
MACRO_GET_4(str, i+4), \
MACRO_GET_4(str, i+8), \
MACRO_GET_4(str, i+12)
#define MACRO_GET_64(str, i) \
MACRO_GET_16(str, i+0), \
MACRO_GET_16(str, i+16), \
MACRO_GET_16(str, i+32), \
MACRO_GET_16(str, i+48)
//CT_STR means Compile-Time_String
#define CT_STR(str) string_t<MACRO_GET_64(#str, 0), 0 >//guard for longer strings
print<CT_STR(Hello World!)>();
@ user1115339 의 답변 에 두 가지 매우 작은 개선 사항을 추가하고 싶습니다 . 대답에 대한 의견에서 그것들을 언급했지만 편의상 여기에 복사 붙여 넣기 솔루션을 넣을 것입니다.
유일한 차이점은 FIXED_CSTRING
매크로이며, 클래스 템플릿 내에서 문자열을 인덱스 연산자에 대한 인수로 사용할 수 있습니다 (예 : 컴파일 타임 맵이있는 경우에 유용함).
라이브 예 .
namespace variadic_toolbox
{
template<unsigned count,
template<unsigned...> class meta_functor, unsigned... indices>
struct apply_range
{
typedef typename apply_range<count-1, meta_functor, count-1, indices...>::result result;
};
template<template<unsigned...> class meta_functor, unsigned... indices>
struct apply_range<0, meta_functor, indices...>
{
typedef typename meta_functor<indices...>::result result;
};
}
namespace compile_time
{
template<char... str>
struct string
{
static constexpr const char chars[sizeof...(str)+1] = {str..., '\0'};
};
template<char... str>
constexpr const char string<str...>::chars[sizeof...(str)+1];
template<typename lambda_str_type>
struct string_builder
{
template<unsigned... indices>
struct produce
{
typedef string<lambda_str_type{}.chars[indices]...> result;
};
};
}
#define CSTRING(string_literal) \
[]{ \
struct constexpr_string_type { const char * chars = string_literal; }; \
return variadic_toolbox::apply_range<sizeof(string_literal)-1, \
compile_time::string_builder<constexpr_string_type>::produce>::result{}; \
}()
#define FIXED_CSTRING(string_literal) \
([]{ \
struct constexpr_string_type { const char * chars = string_literal; }; \
return typename variadic_toolbox::apply_range<sizeof(string_literal)-1, \
compile_time::string_builder<constexpr_string_type>::template produce>::result{}; \
}())
struct A {
auto test() {
return FIXED_CSTRING("blah"); // works
// return CSTRING("blah"); // works too
}
template<typename X>
auto operator[](X) {
return 42;
}
};
template<typename T>
struct B {
auto test() {
// return CSTRING("blah");// does not compile
return FIXED_CSTRING("blah"); // works
}
};
int main() {
A a;
//return a[CSTRING("blah")]; // fails with error: two consecutive ' [ ' shall only introduce an attribute before ' [ ' token
return a[FIXED_CSTRING("blah")];
}
내 자신의 구현은 Boost.Hana
문자열 (가변 문자가있는 템플릿 클래스) 의 접근 방식을 기반으로 하지만 컴파일 시간을 엄격히 검사 하는 C++11
표준 및 constexpr
함수 만 사용합니다 (컴파일 시간 표현식이 아닌 경우 컴파일 시간 오류가 됨). {'a', 'b', 'c' }
매크로 대신 일반 대신 원시 C 문자열로 구성 할 수 있습니다 .
테스트 : https://sourceforge.net/p/tacklelib/tacklelib/HEAD/tree/trunk/src/tests/unit/test_tmpl_string.cpp
사용 예 :
const auto s0 = TACKLE_TMPL_STRING(0, "012"); // "012"
const char c1_s0 = UTILITY_CONSTEXPR_GET(s0, 1); // '1'
const auto s1 = TACKLE_TMPL_STRING(0, "__012", 2); // "012"
const char c1_s1 = UTILITY_CONSTEXPR_GET(s1, 1); // '1'
const auto s2 = TACKLE_TMPL_STRING(0, "__012__", 2, 3); // "012"
const char c1_s2 = UTILITY_CONSTEXPR_GET(s2, 1); // '1'
// TACKLE_TMPL_STRING(0, "012") and TACKLE_TMPL_STRING(1, "012")
// - semantically having different addresses.
// So id can be used to generate new static array class field to store
// a string bytes at different address.
// Can be overloaded in functions with another type to express the compiletimeness between functions:
template <uint64_t id, typename CharT, CharT... tchars>
const overload_resolution_1 & test_overload_resolution(const tackle::tmpl_basic_string<id, CharT, tchars...> &);
template <typename CharT>
const overload_resolution_2 & test_overload_resolution(const tackle::constexpr_basic_string<CharT> &);
// , where `constexpr_basic_string` is another approach which loses
// the compiletimeness between function signature and body border,
// because even in a `constexpr` function the compile time argument
// looses the compiletimeness nature and becomes a runtime one.
constexpr
함수 컴파일 시간 경계 에 대한 세부 사항 : https://www.boost.org/doc/libs/1_65_0/libs/hana/doc/html/index.html#tutorial-appendix-constexpr
다른 사용법에 대한 자세한 내용은 테스트를 참조하십시오.
현재 전체 프로젝트는 실험 중입니다.
참고 URL : https://stackoverflow.com/questions/15858141/conveniently-declaring-compile-time-strings-in-c
'Programing' 카테고리의 다른 글
각 객체에 대해 일반 저장소와 특정 저장소를 작성하는 이점 (0) | 2020.07.01 |
---|---|
_DEBUG vs NDEBUG (0) | 2020.07.01 |
언제 그리고 언제 angular.copy를 사용해야합니까? (0) | 2020.07.01 |
위치와 함께 작동하지 않는 'transform3d': 고정 하위 (0) | 2020.07.01 |
CSS 또는 HTML에 이미지를 data / base64로 포함시켜야합니까? (0) | 2020.07.01 |