strcat是发生在运行期,如何在编译期进行字符串拼接呢,下边是相关代码实例:
#include <iostream>
template<char ... ch>
struct charArray
{
static const char *to_array()
{
static const char arr[sizeof ...(ch) + 1] = {ch...};
return arr;
}
};
template<typename ...T>
struct concat{};
template<char ...ch1, char ...ch2>
struct concat<charArray<ch1...>, charArray<ch2...>>
{
static const char* to_array(){
return charArray<ch1..., ch2...>::to_array();
}
};
int main()
{
std::cout<<charArray<'a','b','c'>::to_array()<<std::endl;
std::cout<<charArray<'e','f','g'>::to_array()<<std::endl;
std::cout<<concat<charArray<'a','b','c'>, charArray<'e', 'f', 'g'>>::to_array()<<std::endl;
return 0;
}