簡體   English   中英

是否可以專門針對模板化類型的模板?

[英]Is it possible to specialize a template for templated types?

對於我的程序,我需要定義一個Solver類,它可以解決問題或嵌套問題。

template< typename ProblemT >
struct Solver {
    static void a() {
        ProblemT::func();
    }
};

template< typename < typename SubT> ProblemT >
struct Solver<ProblemT< SubT> > {
    static void a() {
        ProblemT::func();
        SubT::func();
    }
};

用法:

Solver<Problem1> solver;
Solver<Problem2<Problem3> > nested_solver;

規划 求解的專業版本中,我需要同時了解ProblemTSubT類型,以便正確定義類型並調用正確的函數。

只是一個簡單的錯誤,還是不可能定義這樣的類?

您可以使用模板模板參數來執行此操作:

template<template <typename> class ProblemT, typename SubT>
struct Solver<ProblemT<SubT>>
{
    ...
};

// And you use it like this
Solver<ProblemTemplate<SubProblem>> solver;

您可以嘗試如下操作:

template <typename T>
struct Solver
{
    static void solve() { T::func(); }
};

template <template <typename> class Tmpl, typename U>
struct Solver<Tmpl<U>>
{
    static void solve() { Tmpl<U>::solve(); }
};

顯然,您可以使用其他成員功能來裝飾您的主要Solver模板,您可以在專業化版本中訪問這些成員功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM