簡體   English   中英

使用typedef - 基於模板參數 - 用於類 - 外部類的范圍

[英]Using a typedef – based on template-patameter for class – outside scope of class

如何在類函數的聲明和定義中使用typedef ,它基於我的類的模板參數?

假設我的班級是:

template<class T>
class A
{
    typedef T::T1 X;
    typedef T::T2 Y;

    X& f1(Y& y);
    Y& f2(Y& y);

    // More declarations
};

所以在定義中,我不能只寫:

typedef typename T::T1 X;
typedef typename T::T2 Y;

template<class T>
X& A<T>::f1(Y& y) {...}

template<class T>
Y& A<T>::f2(Y& y) {...}

(在我的情況下, TMaxSimplePathVertex<VertexType<VertexIDType>> ,我還有3個typedef,所以它真的很麻煩)。

我想我可以將所有typedef復制每個函數定義中,但這似乎不是一個優雅的解決方案。

當然,我可以做#define X T1 ,但通常我會聽到人們建議不要使用#define來做這些事情。

那么什么是最好的解決方案?

當您在返回類型中處理模板和成員typedef時,尾隨返回類型可以節省開支。 你可以簡單地說

template<class T>
auto A<T>::f1(Y& y) -> X& {...}

template<class T>
auto A<T>::f2(Y& y) -> X& {...}

A<T>模板中查找成員函數名稱后面出現的內容,這意味着您不需要將A<T>::放在它們前面。

完全拼寫出來,因為當返回類型在方法定義之前時,類型在當前命名空間中計算,而不是類方法的命名空間:

template<class T>
class A
{
    typedef typename T::T1 X;
    typedef typename T::T2 Y;

    X& f1(Y& y);
    Y& f2(Y& y);

    // More declarations
};

template<class T>
typename A<T>::X& A<T>::f1(Y& y) {}

template<class T>
typename A<T>::Y& A<T>::f2(Y& y) {}


struct Foo
{
    using T1 = int;
    using T2 = double;
};

int main()
{
    A<Foo> a;
}

但是當我們使用尾部返回類型時,返回類型將在方法類的上下文中進行計算,因此它變得更容易:

template<class T>
class A
{
    typedef typename T::T1 X;
    typedef typename T::T2 Y;

    X& f1(Y& y);
    Y& f2(Y& y);

    // More declarations
};

template<class T>
auto A<T>::f1(Y& y) -> X&  // <-- this X is a A<T>::X
{}

template<class T>
auto A<T>::f2(Y& y) -> Y& {}


struct Foo
{
    using T1 = int;
    using T2 = double;
};

int main()
{

    A<Foo> a;
}

暫無
暫無

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

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