根据类模板参数,在类中定义或不定义函数 [英] Depending on a class template parameter, define or not define a function in the class

查看:130
本文介绍了根据类模板参数,在类中定义或不定义函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个课程:

template <class Type>
class A
{
public:
    void function1(float a, Type b);
    void function1(float a, float b);
};

现在像这样实例化该类:

Now instantiate the class like this:

A<int> a;

这很好,该类将具有2个具有以下参数的重载函数:(float a,int b); (浮点a,浮点b);

It's fine, this class will have 2 overloaded functions with these parameters: (float a, int b); (float a, float b);

但是当您实例化此类时:

But when you instantiate the class like this:

A<float> a;

您收到编译错误:

重新声明了

成员函数.

member function redeclared.

因此,根据Type的类型,我将(或不希望)编译器定义函数,如下所示:

So, depending on the type of Type, I wan't (or don't want) the compiler to define a function, something like this:

template <class Type>
class A
{
public:
    void function1(float a, Type b);

    #if Type != float
    void function1(float a, float b);
    #endif
};

但是,当然,上面的语法不起作用.是否可以在C ++中执行这样的任务?如有可能,请提供示例.

But, of course, the syntax above doesn't work. Is it possible to perform such a task in C++? If possible, please provide an example.

推荐答案

您可以使用模板特化:

template <class Type>
class A {
public:
    void function1(float a, Type b) {
    }
    void function1(float a, float b) {
    }
};

template <>
class A<float> {
public:
    void function1(float a, float b) {
    }
};

// ...

A<int> a_int;
a_int.function1(23.4f, 1);
a_int.function1(23.4f, 56.7f);

A<float> a_float;
a_float.function1(23.4f, 56.7f);

-编辑---

如果您有大量的常用功能,则可以执行以下操作:

--- EDIT ---

If you have a large number of common functions, you could do something like this:

class AImp {
public:
    void function1(float a, float b) {
    }
    void function1(float a, double b) {
    }
    void function1(float a, const std::string& b) {
    }
    // Other functions...
};

template <class Type>
class A : public AImp {
public:
    void function1(float a, Type b) {
    }
    using AImp::function1;
};

template <>
class A<float> : public AImp {
};

// ...

A<int> a_int;
a_int.function1(23.4f, 1);
a_int.function1(23.4f, 56.7f);
a_int.function1(23.4f, 56.7);
a_int.function1(23.4f, "bar");

A<float> a_float;
a_float.function1(23.4f, 56.7f);
a_float.function1(23.4f, 56.7);
a_float.function1(23.4f, "bar");

这篇关于根据类模板参数,在类中定义或不定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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