【问题标题】:Match class template with default template parameters as a template argument with fewer parameters将具有默认模板参数的类模板匹配为具有较少参数的模板参数
【发布时间】:2014-06-16 13:15:27
【问题描述】:

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

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++ templates


    【解决方案1】:

    如果你使用的是 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++。可能会开始写下切换到 C++11 的原因列表 ...
    猜你喜欢
    • 2011-10-01
    • 1970-01-01
    • 2015-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    • 2018-10-12
    • 1970-01-01
    相关资源
    最近更新 更多