2016-07-04 137 views
1

我有以下的(简化)代码:在模板类使用模板功能

#include <iostream> 

class Foo { 
public: 
    template<class T> 
    static size_t f() { 
    return sizeof(T); 
    } 
}; 

template<class A> 
class Bar { 
public: 
    template<class B> 
    static void f(B const& b) { 
    std::cout << A::f<B>() << std::endl; 
    } 
}; 

int main() { 
    Bar<Foo>::f(3.0); 
    return 0; 
} 

它编译于MSVC罚款,但在海湾合作委员会(5.2.1),它提供了以下错误:

main.cpp:16:26: error: expected primary-expression before ‘>’ token 
    std::cout << A::f<B>() << std::endl; 
         ^

(后面跟着几百行与cout相关的错误)。我想它不知道A::f可以作为模板函数吗?它是否破坏了标准中的任何内容?

回答

3

你需要把关键字template

std::cout << A::template f<B>() << std::endl; 

你需要把它,因为A是一个从属名称,否则编译器可以解释为一个比较操作:

A::f < B 
+1

谢谢,正是我所期待的。 MSVC是非常原谅这些关键字:((我猜它甚至不尝试解析函数体,直到它需要实例化它)。 – riv