c++ - 嵌套模板

标签 c++ 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 是从属名称,因此您必须明确指定它们是类型名称,而不是静态数据成员等。 See this详情

关于c++ - 嵌套模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5511492/

相关文章:

c++ - 即使在 Visual C++ 编译器中,在模板中传递 "const char"参数时也会遇到一些问题 Nov 2013 CTP

c++ - STL 是否有助于在 C++ 中以更快的方式搜索大数组?

c++ - 如何提供用于创建静态和动态大小 vector 的通用接口(interface)?

boost - 找到 map 中显示的 vector 元素

c++ - 如何从可变模板参数的嵌套类派生?

angularjs - 你如何使用 gulp-angular-templatecache 和 gulp-usemin

c++ - 在 C++ 中声明方法 extern

类型为 "void(*)(int wall) is incompatible with parameter of type "int 的 C++ 参数”

c++ - 对包含圆圈的列表进行排序 C++

c++ - 什么是 C++ 中的代理类