C++ - 使用该方法的部分特化重载模板类方法

标签 c++ templates overloading partial-specialization

堆栈溢出中已经有一些与此类似的问题,但似乎没有任何问题可以直接回答我的问题。如果我重新发布,我深表歉意。

我想用这些方法的部分模板特化来重载模板化类(带有 2 个模板参数)的一些方法。我一直无法找出正确的语法,并且开始认为这是不可能的。我想我会在这里发帖看看是否能得到确认。

要遵循的示例代码:

template <typename T, typename U>
class Test
{
public:
    void Set( T t, U u ); 

    T m_T;
    U m_U;
};

// Fully templated method that should be used most of the time
template <typename T, typename U>
inline void Test<T,U>::Set( T t, U u )
{
    m_T=t;
    m_U=u;
}

// Partial specialisation that should only be used when U is a float.
// This generates compile errors
template <typename T>
inline void Test<T,float>::Set( T t, float u )
{
    m_T=t;
    m_U=u+0.5f;
}


int _tmain(int argc, _TCHAR* argv[])
{
    Test<int, int> testOne;    
    int a = 1;
    testOne.Set( a, a );

    Test<int, float> testTwo;    
    float f = 1.f;
    testTwo.Set( a, f );
}

我知道我可以编写整个类的部分特化,但这有点糟透了。这样的事情可能吗?

(我使用的是 VS2008) 编辑:这是编译错误 错误 C2244:“Test::Set”:无法将函数定义与现有声明相匹配

谢谢:)

最佳答案

如果不定义类模板本身的部分特化,就不能部分特化一个成员函数。请注意,模板的部分特化仍然是一个模板,因此当编译器看到 Test<T, float> 时,它期望类模板的部分特化。

--

C++ 标准 (2003) 中的 $14.5.4.3/1 说,

The template parameter list of a member of a class template partial specialization shall match the template parameter list of the class template partial specialization. The template argument list of a member of a class template partial specialization shall match the template argument list of the class template partial specialization. A class template specialization is a distinct template. The members of the class template partial specialization are unrelated to the members of the primary template. Class template partial specialization members that are used in a way that requires a definition shall be defined; the definitions of members of the primary template are never used as definitions for members of a class template partial specialization. An explicit specialization of a member of a class template partial specialization is declared in the same way as an explicit specialization of the primary template.

然后标准本身给出了这个例子,

// primary template
template<class T, int I> struct A {
void f();
};
template<class T, int I> void A<T,I>::f() { }

// class template partial specialization
template<class T> struct A<T,2> {
void f();
void g();
void h();
};
// member of class template partial specialization
template<class T> void A<T,2>::g() { }

我希望标准中的引文和示例能够很好地回答您的问题。

关于C++ - 使用该方法的部分特化重载模板类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5206080/

相关文章:

c++ - Makefiles : specific 'no input files' , 自动变量

C++ 使用 vector 加载 500MB 数据使用 5GB RAM

c++ - 类模板、矩阵和加法

具有不同类型的非类型参数的 C++ 可变参数模板

java - 重载可变参数方法时的奇怪行为

java - 重载是编译时多态性。真的吗?

c++ - 类名和同名变量的声明

c++ - 模板成员函数的参数推导不适用于在函数内部声明的类?

java - 方法内重载构造函数 InnerClass

c++ - 创建 QApplication 在 4k 显示器上以高 dpi 显示时调整父窗口(非 Qt 窗口)的大小