从其他参数派生模板参数但保持智能感知
Derive template arguments from other argument but keep intelli sense
假设我有以下 类:
template<typename A> class Foo { ... };
template<typename A, typename B = Foo<A>> class Bar { ... };
Bar 是虚拟的,它可以用 A 和 B 的许多不同参数派生。模板的目的是为派生提供智能感知。我不想为 A 和 B 使用接口,因为它们没有任何共同点。而且,这会导致很多不必要的转换。
问题是我还想提供各种使用Bar的算法,有的是通用的,有的是专用的。我试过的东西看起来像这样:
template<typename A, typename B = Foo<A>, typename BarType = Bar<A, B>>
class Algorithm
{
void doWork(BarType& bar) { ... };
};
我想做的是将 Bar 的推导传递给算法,它应该会自动检测参数 A 和 B。例如:
class BarDerivation : Bar<int, Foo<int>> { ... };
Algorithm<BarDerivation> alg;
这个answer提供了一个使用type-traits的解决方案,问题是算法会丢失BarType来自Bar类型的信息。
我不确定我正在做的事情是否是实现我想要实现的目标的最佳方法。那么有没有办法解决我的问题,或者有更好的方法吗?
更简单的方法是在 Foo/Bar 中添加别名:
template<typename A> class Foo { using type = A; };
template<typename A, typename B = Foo<A>> class Bar { using T1 = A; using T2 = B; };
class Derived : Bar<int, Foo<float>> { /*...*/ };
template <typename BarType>
class Algorithm
{
using A = typename BarType::T1;
using B = typename BarType::T2;
void doWork(BarType& bar) { ... };
};
假设我有以下 类:
template<typename A> class Foo { ... };
template<typename A, typename B = Foo<A>> class Bar { ... };
Bar 是虚拟的,它可以用 A 和 B 的许多不同参数派生。模板的目的是为派生提供智能感知。我不想为 A 和 B 使用接口,因为它们没有任何共同点。而且,这会导致很多不必要的转换。
问题是我还想提供各种使用Bar的算法,有的是通用的,有的是专用的。我试过的东西看起来像这样:
template<typename A, typename B = Foo<A>, typename BarType = Bar<A, B>>
class Algorithm
{
void doWork(BarType& bar) { ... };
};
我想做的是将 Bar 的推导传递给算法,它应该会自动检测参数 A 和 B。例如:
class BarDerivation : Bar<int, Foo<int>> { ... };
Algorithm<BarDerivation> alg;
这个answer提供了一个使用type-traits的解决方案,问题是算法会丢失BarType来自Bar类型的信息。 我不确定我正在做的事情是否是实现我想要实现的目标的最佳方法。那么有没有办法解决我的问题,或者有更好的方法吗?
更简单的方法是在 Foo/Bar 中添加别名:
template<typename A> class Foo { using type = A; };
template<typename A, typename B = Foo<A>> class Bar { using T1 = A; using T2 = B; };
class Derived : Bar<int, Foo<float>> { /*...*/ };
template <typename BarType>
class Algorithm
{
using A = typename BarType::T1;
using B = typename BarType::T2;
void doWork(BarType& bar) { ... };
};