我不明白为什么在直接调用静态方法模板时成功,但在通过函数模板调用时却不行。
#include <iostream>
#include <type_traits>
template <typename A>
class Test {
public:
template <typename B>
static void test() {
if (std::is_same<A, B>::value)
std::cout << "Type A and Type B are the same\n";
else
std::cout << "Type A and Type B are not the same\n";
}
};
template <typename C, typename D>
void test() {
Test<C>::test<D>();
}
int main(int argc, char* argv[]) {
Test<int>::test<int>();
Test<int>::test<char>();
test<int, char>();
test<int, int>();
return 0;
}
使用命令行编译:
g++ -std=c++11 test.cpp
使用:
$ g++ --version
g++ (Ubuntu 4.9.2-0ubuntu1~14.04) 4.9.2
Copyright (C) 2014 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
并且遇到了这些错误:
test.cpp: In function ‘void test()’:
test.cpp:18:20: error: expected primary-expression before ‘>’ token
Test<C>::test<D>();
^
test.cpp:18:22: error: expected primary-expression before ‘)’ token
Test<C>::test<D>();
^
答案 0 :(得分:2)
test
是一个从属名称:
template <typename C, typename D>
void test() {
Test<C>::test<D>();
^^^^^^^^^
}
因此,您需要通知编译器它是一个模板:
template <typename C, typename D>
void test() {
Test<C>::template test<D>();
}
答案 1 :(得分:1)
对于从属名称,您需要告诉编译器该名称是模板:
Test<C>::template test<D>();