我有一堆看起来像这样的模板:
template <class Graph>
class LinearSolver_A { /* ... */ };
template <class Graph, class Optional1 = int, class Optional2 = double>
class LinearSolver_B { /* ... */ };
现在,我有另一个模板,它需要这些求解器作为参数:
template <template <class> class LinSolver>
class SolverRunner { /* ... */ };
struct solver_not_compiled_t {}; // just a simple structure
template <>
class SolverRunner<solver_not_compiled_t> { /* ... */ };
// there is also a specialization of SolverRunner, in case it matters
我的问题是,只有具有单个模板参数的线性求解器(例如 LinearSolver_A
)才能作为 SolverRunner
的参数匹配。但是,如果有任何可选参数(如 LinearSolver_B
),即使提供了默认值,它们也无法匹配。
我认为 typename
不能使用,因为模板不是完整的类型。如何解决?我会接受带有包装器的解决方案,但包装器本身需要是一个模板,我们又回到了同样的问题。我想这可以通过为每个 LinearSolver_?
编写不同类型的包装器来解决,但这要么是大量的复制粘贴,要么是一些预处理器魔术——真的没有办法在干净的 C++ 方式?
这有点类似于 Why the template with default template arguments can't be used as template with less template argument in Template Template Parameters除非作者没有要求解决方案——我真的很想使用这些模板。
遗憾的是,没有 C++11。
最佳答案
如果您使用的是 C++11,那么您可以使用 template aliases :
template <class Graph>
using LinearSolver_B_Defaults = LinearSolver_B<Graph>;
template <>
class SolverRunner<LinearSolver_B_Defaults> { /* ... */ };
编辑:由于您不能使用此功能,您可以这样做:
template <class Graph, class Optional1 = int, class Optional2 = double>
class LinearSolver_B { /* ... */ };
template <class Graph>
struct LinearSolver_B_Applier
{
typedef LinearSolver_B<Graph> type;
};
template <>
class SolverRunner<LinearSolver_B_Applier>
{
// Use typename LinearSolver_B_Applier<T>::type inside here.
};
关于c++ - 将具有默认模板参数的类模板匹配为具有较少参数的模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24244656/