簡體   English   中英

嵌套模板

[英]Nested Templates

我有一個C ++模板的奇怪問題,我不明白為什么以下代碼不起作用:

#include <iostream>

template <typename A, typename B>
class TypePair {
public:
    typedef A First;
    typedef B Second;
};


template <typename P>
class Foo {
    public:
        Foo(P::First f, P::Second) {
            std::cout
                << "first = " << f << std::endl
                << "second = " << s << std::endl;
        }
};


int main(int argc, char **argv) {
    Foo<TypePair<int, double> > foo(42, 23.0);

    return 0;
}

該代碼產生以下錯誤:

$ g++ templates.cpp -o templates
templates.cpp:14: error: expected ‘)’ before ‘f’
templates.cpp: In function ‘int main(int, char**)’:
templates.cpp:23: error: no matching function for call to ‘Foo<TypePair<int, double> >::Foo(int, double)’
templates.cpp:12: note: candidates are: Foo<TypePair<int, double> >::Foo()
templates.cpp:12: note:                 Foo<TypePair<int, double> >::Foo(const Foo<TypePair<int, double> >&)

對我來說,代碼看起來完全沒問題,但是g ++顯然有自己的看法^^有什么想法嗎?

塞巴斯蒂安

使用

Foo(typename P::First f, typename P::Second s)

由於P是模板參數,因此P :: First和P :: Second是從屬名稱,因此您必須明確指定它們是類型名稱,而不是靜態數據成員。 有關詳細信息, 請參見

暫無
暫無

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

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