我有一个带有模板成员函数的模板类。我想显式实例化该类以避免编译速度急剧下降。我正在使用 g++ 4.1.2。我从编译器得到模棱两可的模板专业化错误。这是重现问题的最短代码:
template <class T, class S >
class Test
{
public:
template< typename T1 >
void* get( const T1& );
void* get(const int& ); //Specialization of the above
};
typedef Test<int, double> foo;
//instantiate
inline template class Test<int, double>;
template void* foo::get(int const&);
我不想使用包罗万象:
template class Test<int, double>
因为重载 get(const int&) 不会为所有可能的显式实例定义,因此编译器会抛出不支持它的类型。
此代码在 Visual Studio 中编译(没有内联前面的模板,这是一个 gcc 特定的扩展)。有人可以解释一下我是如何编译这个代码片段的吗?
更新:这是我得到的错误:
g++ -c -o template.o template.cpp
template.cpp:14: error: ambiguous template specialization ‘get<>’ for ‘void* Test<int, double>::get(const int&)’
template.cpp:7: error: candidates are: void* Test<T, S>::get(const int&) [with T = int, S = double]
template.cpp:6: error: template<class T1> void* Test::get(const T1&) [with T1 = T1, T = int, S = double]
UPDATE2:感谢您的解决方案,但它无法编译。类内不允许专业化。错误是:
g++ -c -o template.o template.cpp
template.cpp:7: error: explicit specialization in non-namespace scope ‘class Test<T, S>’
template.cpp:7: error: enclosing class templates are not explicitly specialized
template.cpp:8: error: ‘get’ is not a template function
template.cpp: In instantiation of ‘void* Test<T, S>::get(const T1&) [with T1 = int, T = int, S = double]’:
template.cpp:15: instantiated from here
template.cpp:15: error: explicit instantiation of ‘void* Test<T, S>::get(const T1&) [with T1 = int, T = int, S = double]’ but no definition available
make: *** [template.o] Error 1