引用模板(别名?)的语法

Syntax to refer to a template (alias?)

本文关键字:语法 别名 引用      更新时间:2023-10-16

我正在将一些Julia代码移植到c++中,并且遇到了一个问题。更糟糕的是,我对c++的命名法不太熟悉,所以没能在谷歌上找到出路。

基本上,我想弄清楚如何引用模板(这是模板别名吗?),以便我可以稍后使用它,即引用类型。我尝试了各种咒语涉及using, typenametemplate,但似乎没有什么让我的编译器高兴。我已经设法生产了一些我想要的东西(见下文),但它很讨厌。有没有更好的办法?任何合理的c++都可以。

下面的代码是我试图实现的最小示例

#include <iostream>
#include <type_traits>
template<int n, template<int> class T>
int unwrap(T<n>& x) { return n; }
template<int n>
struct A { static const char name = 'A'; };
template<int n>
struct B { static const char name = 'B'; };
template<bool flag>
struct promote_if {
    template<int n> using type = A<n>;
};
template<> 
struct promote_if<true> {
    template<int n> using type = B<n>;
};
template<int m, int n, 
template<int> class X, 
template<int> class Y, 
template<int> class Z>
struct Stuff { static const int seven = 7; };
// Add type parameters and return 
// B<m + n> if X or Y is a B,
// otherwise return A<m + n>
template<int m, int n, template<int> class X, template<int> class Y> 
auto add(X<m>& x, Y<n>& y) {
    static const bool any = std::is_base_of<B<m>, X<m>>::value || std::is_base_of<B<n>, Y<n>>::value;
    // This works, but is gross
    std::cout << Stuff<m,n,promote_if<any>::template type,X,Y>::seven << "n";
    typename promote_if<any>::template type<m + n> z;
    // Something like this is what I'm trying to achieve
    // using T = typename promote_if<any>::template type;
    // T<m + n> z;
    // std::cout << Stuff<m,n,T,X,Y>::seven << "n";
    return z;
}
int main(int argc, char const *argv[]) {
    A<1> a;
    B<2> b;
    auto c = add(a, a);
    std::cout << "c = add(a, a) = " << c.name << "<" << unwrap(c) << ">n";
    auto d = add(a, b);
    std::cout << "d = add(a, b) = " << d.name << "<" << unwrap(d) << ">n";
    return 0;
}
// Output
// Stuff is 7
// c = add(a, a) = A<2>
// Stuff is 7
// d = add(a, b) = B<3>

代替

template<int m, int n, template<int> class X, template<int> class Y> 
auto add(X<m>& x, Y<n>& y) {
    static const bool any = std::is_base_of<B<m>, X<m>>::value || std::is_base_of<B<n>, Y<n>>::value;
    // This works, but is gross
    std::cout << Stuff<m,n,promote_if<any>::template type,X,Y>::seven << "n";
    typename promote_if<any>::template type<m + n> z;
    // Something like this is what I'm trying to achieve
    // using T = typename promote_if<any>::template type;
    // T<m + n> z;
    // std::cout << Stuff<m,n,T,X,Y>::seven << "n";
    return z;
}

// Add type parameters and return 
// B<m + n> if X or Y is a B,
// otherwise return A<m + n>
template<int m, int n, template<int> class X, template<int> class Y> 
auto add(X<m>& x, Y<n>& y) {
    static const bool any = std::is_base_of<B<m>, X<m>>::value || std::is_base_of<B<n>, Y<n>>::value;
    using T = promote_if<any>;
    typename T::template type<m + n> z;
    std::cout << Stuff<m,n,T::template type,X,Y>::seven << "n";
    return z;
}

我只是尝试了typenametemplate等的一些组合,让g++编译器的诊断引导我走向工作代码。

我认为这仍然是丑陋的。

一个更好的解决方案可能是重新考虑整个事情并改变设计。