我正在将一些 Julia 代码移植到 C++,但遇到了问题。更糟糕的是,我对 C++ 命名法不是很熟悉,所以无法用 google 搜索出路。
基本上,我正在尝试弄清楚如何引用模板(这是模板别名吗?)以便我以后可以使用它,即引用一个类型。我尝试了各种涉及using
、typename
和template
的方法,但似乎没有什么能让我的编译器满意。我设法制作了一些可以满足我要求的东西(见下文),但它非常糟糕。有没有更好的办法?任何合理的 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;
}
我刚刚尝试了 typename
和 template
等的一些组合,让 g++ 编译器的诊断引导我找到工作代码。
不过,我认为这仍然很难看。
一个可能更好的解决方案是重新考虑整个事情并更改设计。
关于c++ - 引用模板的语法(别名?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38965644/