C++组合参数模板元编程

C++ combining arguments template metaprogramming

本文关键字:编程 组合 参数 C++      更新时间:2023-10-16

我是C++中模板和元编程的新手。我现在要做的是:我有一个带有模板的结构,它需要类型为char的非类型可变包,定义如下:

template <char ... chs> 
struct MyStruct
{};

我有第二个结构模板,它需要两种类型,如下所示:

template <typename ch1, typename ch2>
struct Together
{
};

我正在努力实现的是:

cout << Together<MyStruct<'a','b'>, MyStruct<'c','d'>>::result << 'n';

必须打印:abcd

提前感谢

使用模板,可以通过部分专业化实现模式匹配。像这样声明主模板声明:

template <typename First, typename Second>
struct Together;

然后以某种方式定义具有"外观"的类型的部分专业化:

template <char... ch1s, char... ch2s>
struct Together<MyStruct<ch1s...>, MyStruct<ch2s...>>
{
  std::string result;
  Together() : result({ch1s..., ch2s...}){}
};

这是一个可能的解决方案,使用std::string result:与问题非常匹配

template <char ... chs>
struct MyStruct
{
    static string stringify()
    {
        return stringify(chs...);
    }
    template <typename ... cst>
    static string stringify()
    {
        return string();
    }
    template <typename T, typename ... cst>
    static string stringify(T c, cst... cs)
    {
        return string() + c + stringify<cst...>(cs...);
    }
};
template <typename ch1, typename ch2>
struct Together
{
    static string result() {return ch1::stringify() + ch2::stringify();}
};
int main() {
    cout << Together<MyStruct<'a','b'>, MyStruct<'c','d'>>::result() << 'n';
    return 0;
}

它当然会或多或少地使用模板参数,比如:

Together<MyStruct<'a','b','c','d'>, MyStruct<'e','f','g'>>::result()

以下是@Ryan Haining的答案的一个小改进:

template <char... Chars>
struct MyStruct
{
    static constexpr char value[] {Chars..., ''};
};
template <char... Chars>
constexpr char MyStruct<Chars...>::value[];
template <typename, typename>
struct Together;
template <char... Chars1, char... Chars2>
struct Together<MyStruct<Chars1...>, MyStruct<Chars2...>>
{
    using type = MyStruct<Chars1..., Chars2...>;
};

现场演示