Ste*_* Lu 5 c++ string templates template-meta-programming c++11
目前我有:
template <typename T> struct typename_struct<T*> {
static char const* name() {
return (std::string(typename_struct<T>::name()) + "*").c_str();
}
};
Run Code Online (Sandbox Code Playgroud)
我想知道我是否可以避免在我被迫分配字符串来执行连接的整个位置.
这一切都发生在编译时,即我打算"int****"在引用时获取字符串typename_struct<int****>::name().(假设我已经声明了相应的int返回专门化"int")
在编写代码时,编译器是否仅在编译时使用std :: string进行串联?(我会好的)或者这样的调用会在运行时导致基于4 std :: string的连接吗?(我不会那么好)
你可以使用这样的东西.一切都在编译时发生.使用baseize_typename_struct来定义基本类型.
template <const char* str, int len, char... suffix>
struct append {
static constexpr const char* value() {
return append<str, len-1, str[len-1], suffix...>::value();
}
};
template <const char* str, char... suffix>
struct append<str, 0, suffix...> {
static const char value_str[];
static constexpr const char* value() {
return value_str;
}
};
template <const char* str, char... suffix>
const char append<str, 0, suffix...>::value_str[] = { suffix..., 0 };
template <typename T>
struct base_typename_struct;
template <>
struct base_typename_struct<int> {
static constexpr const char name[] = "int";
};
template <typename T, char... suffix>
struct typename_struct {
typedef base_typename_struct<T> base;
static const char* name() {
return append<base::name, sizeof(base::name)-1, suffix...>::value();
}
};
template <typename T, char... suffix>
struct typename_struct<T*, suffix...>:
public typename_struct<T, '*', suffix...> {
};
int main() {
cout << typename_struct<int****>::name() << endl;
}
Run Code Online (Sandbox Code Playgroud)
不使用递归模板的替代方法(但需要 C++14):
#include <utility>
template<int...I> using is = std::integer_sequence<int,I...>;
template<int N> using make_is = std::make_integer_sequence<int,N>;
constexpr auto size(const char*s) { int i = 0; while(*s!=0){++i;++s;} return i; }
template<const char*, typename, const char*, typename>
struct concat_impl;
template<const char* S1, int... I1, const char* S2, int... I2>
struct concat_impl<S1, is<I1...>, S2, is<I2...>> {
static constexpr const char value[]
{
S1[I1]..., S2[I2]..., 0
};
};
template<const char* S1, const char* S2>
constexpr auto concat {
concat_impl<S1, make_is<size(S1)>, S2, make_is<size(S2)>>::value
};
Run Code Online (Sandbox Code Playgroud)
例子:
constexpr const char a[] = "int";
constexpr const char c[] = "**";
#include <iostream>
int main()
{
std::cout << concat<a,b> << '\n';
}
Run Code Online (Sandbox Code Playgroud)
append字符转字符串也可以这样实现,将第二个const char*参数替换为char....