c++ - 将具有默认模板参数的类模板匹配为具有较少参数的模板参数

标签 c++ templates

我有一堆看起来像这样的模板:

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/

相关文章:

c++ - VS2017 C++ : Howto supress warnings after "Generating Code..."

解决方案的 C++ 替代算法

c++ - 使用 Teigha 4.1.1 计算偏移曲线

c++ - C++ 中的内部类会自动成为 friend 吗?

javascript - 使用 Dustjs 进行 Angular 模板化

c++ - 为模板类嵌套类定义 std::hash 的编译错误

javascript - Tornado 和 JavaScript 库的问题

c++ - 如何在 C++ 中获取指针的索引?

c++ - 可变参数模板索引包扩展

c++ - 自动将类定义与声明分开?