簡體   English   中英

部分特化不使用任何模板參數

[英]Partial specialization does not use any of its template parameters

我正在嘗試使用模板元編程實現元組,但是我遇到了索引函數get Tuple類型的實現是這樣的:

template<typename A, typename... B>
class Tuple : Tuple<B...> {
    private:
        A val;
    public:
        using Base = Tuple<B...>;
        Base* base() {
            return static_cast<Base*>(this);
        }
        const Base* base() const {
            return static_cast<const Base*>(this);
        }
        Tuple(A a, B... b): Base(b...), val(a) { }
        A first() {
            return val;
        }
};

template<class A>
class Tuple<A> {
    private:
        A val;
    public:
        Tuple(A a): val{a} {}
        A first() {
            return val;
        }
};

get結構的實現是:

template<int N, class... A>
struct get {
    select<N,A...> operator()(Tuple<A...> t) {
        return get<N-1>()(t.base());
    }
};

template<class R, class... A>
struct get<0> {
    R operator()(Tuple<R, A...> t) {
        return t.first();
    }
};

這是編譯器給我的錯誤:

tuple.cpp:53:8: error: partial specialization of 'get' does not use any of its template parameters
struct get<0> {
       ^
1 error generated.

為什么我收到此錯誤? 我該如何糾正?

注意: select<N,A...>是一個類型函數,它從A選擇第N個索引處的類型。

也許你必須部分專業化get如下

template<class R, class... A>
struct get<0, R, A...> {
    R operator()(Tuple<R, A...> t) {
        return t.first();
    }
};

我的意思是...... get<0, R, A...> ,而不是get<0>

但是你還要修改main get以使用正確的類型列表調用以下調用,所以

template<int N, typename A0, typename ... As>
struct get {
    auto operator()(Tuple<A0, As...> t) {
        return get<N-1, As...>()(t.base());
    }
};

否則,您還可以將類型管理請求到operator()的模板版本,並僅維護getint N

template <int N>
struct get
 {
   template <typename Tpl>
   auto operator() (Tpl t)
      -> decltype( get<N-1>()(t.base()) )
    { return get<N-1>()(t.base()); }
 };

template<>
struct get<0>
 {
   template <typename Tpl>
   auto operator() (Tpl t)
      -> decltype ( t.first() )
    { return t.first(); }
 };

從C ++ 14開始,您可以避免使用decltype()部分。

非主題建議:避免使用可能與std命名空間名稱沖突的名稱。

也許myGetmyTuple而不是getTuple

否則你可以將所有內容放在個人命名空間中(所以myNs::getmyNs::Tuple

你的get主要模板是:

template<int N, class... A>
struct get{ ... };

get的部分專業是:

template<class R, class... A>
struct get<0>{ ... };

專門化是接收單個模板參數,即: 0 ,但上面的主模板有兩個模板參數:

  • 非類型模板參數N
  • 可變參數類型參數A

此外,如何推斷出R


專業化get

template<class R, class... A>
struct get<0, R, A...>{ ... };

將推導出R :它將被推導為傳遞的可變參數的第一個元素的類型。 例如,在:

get<0, int, float, double> foo;

R將被推導為int

暫無
暫無

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

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