1

我现在一直在尝试以多种方式分析这个问题,但我无法弄清楚。

我的用例是 - 我有一个模板类,我想为特定类型提供特定实现,同时为其余部分保留通用实现。

这是代码:

template< typename T >
struct SomeClass
{
    void foo();
};

template< typename T >
void SomeClass< T >::foo()
{
    printf( "generic impl." );
}

template<>
void SomeClass< char >::foo()
{
    printf( "char-specific impl." );
}

一切正常,只要整个代码位于使用它的代码旁边的 CPP 文件中。

一旦我将代码移动到专用文件,如下所示:

一些类.h

#ifdef _SOME_CLASS_H

template< typename T >
struct SomeClass
{
    void foo();
};

template< typename T >
void SomeClass< T >::foo()
{
    printf( "generic impl." );
}

#endif 

SomeClass.cpp

#include "SomeClass.h"

template<>
void SomeClass< char >::foo()
{
    printf( "char-specific impl." );
}

我收到一个链接器错误,提示 void SomeClass< char >::foo() 已经实现。

任何想法为什么?

4

2 回答 2

2

将专用函数成员的前向声明添加到标题中:

template<> void SomeClass<char>::foo();
于 2012-10-16T21:36:26.003 回答
1

为了声明专用模板类的成员函数,您需要首先定义专用类:

template <>
struct SomeClass<char>
{
  void foo ();
};

只有这样你才能定义实际的函数实现:

template <>
void SomeClass<char>::foo () { /* do something */ }
于 2012-10-16T20:05:26.593 回答