C ++-重载了模板化的类方法,并对该方法进行了部分规范化 [英] C++ - Overload templated class method with a partial specilization of that method

查看:140
本文介绍了C ++-重载了模板化的类方法,并对该方法进行了部分规范化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已经有一些与此栈溢出已经类似的问题,但是似乎没有什么可以直接回答我的问题.如果我要重新发布,我深表歉意.

There are a few questions already similar to this already on stack overflow, but nothing that seemd to directly answer the question I have. I do apologise if I am reposting.

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

I'd like to overload a few methods of a templated class (with 2 template parameters) with a partial template specialisation of those methods. I haven't been able to figure out the correct syntax, and am starting to think that it's not possible. I thought I'd post here to see if I can get confirmation.

要遵循的示例代码:

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 );
}

我知道我可以写整个课程的部分专业知识,但这有点糟.这样可能吗?

I know that I could write a partial specialisation of the entire class, but that kinda sucks. Is something like this possible?

(我正在使用VS2008) 这是编译错误 错误C2244:"Test :: Set":无法将函数定义与现有声明匹配

(I'm using VS2008) Here is the compile error error C2244: 'Test::Set' : unable to match function definition to an existing declaration

谢谢:)

推荐答案

要绘制的特定问题很容易:

The particular problem you're sketching is easy:

template< class T >
inline T foo( T const& v ) { return v; }

template<>
float foo( float const& v ) { return v+0.5; }

然后从Test::Set实现中调用foo.

如果您想获得全部通用性,请类似地使用具有静态帮助器成员函数的帮助器类,并部分地专门化该帮助器类.

If you want the full generality, then similarly use a helper class with static helper member functions, and partially specialize that helper class.

干杯hth.,

这篇关于C ++-重载了模板化的类方法,并对该方法进行了部分规范化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆