在模板中使用模板函数 class
Using a template function in a template class
我有以下(简化的)代码:
#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 中编译良好,但在 GCC (5.2.1) 中出现以下错误:
main.cpp:16:26: error: expected primary-expression before ‘>’ token
std::cout << A::f<B>() << std::endl;
^
(后面是几百行与 cout 相关的错误)。我想它没有意识到 A::f
可以是模板函数?它是否违反了标准?
您需要输入关键字template
:
std::cout << A::template f<B>() << std::endl;
因为A
是从属名所以需要写,否则编译器会把它解释为比较运算符:
A::f < B
我有以下(简化的)代码:
#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 中编译良好,但在 GCC (5.2.1) 中出现以下错误:
main.cpp:16:26: error: expected primary-expression before ‘>’ token
std::cout << A::f<B>() << std::endl;
^
(后面是几百行与 cout 相关的错误)。我想它没有意识到 A::f
可以是模板函数?它是否违反了标准?
您需要输入关键字template
:
std::cout << A::template f<B>() << std::endl;
因为A
是从属名所以需要写,否则编译器会把它解释为比较运算符:
A::f < B