看这个例子:
template <typename A>
struct Foo1 {};
template <typename A, typename B>
struct Foo2 {};
struct Bar1 {
template <typename A>
using Foo = Foo1<A>;
};
struct Bar2 {
template <typename A, typename B>
using Foo = Foo2<A, B>;
};
template <typename BAR>
struct Something {
template <typename ...P>
void func(typename BAR::template Foo<P...> foo) {
}
};
我想实现:如果Something
专门用于 Bar1
, 那么我想要一个模板函数 func
,即:
template <typename A>
void func(Foo1<A> foo)
如果Something
专门用于 Bar2
, 然后 func
应该是:
template <typename A, typename B>
void func(Foo2<A, B> foo)
但是,这种直截了当的方法是行不通的,因为 clang 会报错(你需要实例化 Something<BarX>
才能让 clang 报告这个错误):
error: pack expansion used as argument for non-pack parameter of alias template void func(typename BAR::template Foo<P...> foo) {
所以看起来别名模板不是 100% 透明的(我发现了一些关于这个的讨论:CWG 1430,这是设计使然)。
是否有解决此问题的方法?
(gcc 编译此代码,但根据 CWG 1430,这可能是无意的)
最佳答案
解决方法是使别名可变:
struct Bar1 {
template <typename... Ts>
using Foo = Foo1<Ts...>;
};
struct Bar2 {
template <typename... Ts>
using Foo = Foo2<Ts...>;
};
关于c++ - 将参数包传递给别名模板(具有非包参数)的解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70744937/