根据类模板参数,定义或不定义类中的函数

Vad*_*dim 8 c++ parameters templates function

假设我们有一个班级:

template <class Type>
class A
{
public:
    void function1(float a, Type b);
    void function1(float a, float b);
};
Run Code Online (Sandbox Code Playgroud)

现在实例化这样的类:

A<int> a;
Run Code Online (Sandbox Code Playgroud)

没关系,这个类将有2个带有这些参数的重载函数:(float a,int b); (浮动a,浮动b);

但是当你像这样实例化这个类:

A<float> a;
Run Code Online (Sandbox Code Playgroud)

你得到编译错误:

成员函数重新声明.

所以,根据Type的类型,我不想(或者不想)编译器定义一个函数,如下所示:

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

    #if Type != float
    void function1(float a, float b);
    #endif
};
Run Code Online (Sandbox Code Playgroud)

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

inf*_*inf 9

你可以使用一些C++11 std::enable_if:

template <class Type>
class A
{
public:
    template<typename t = Type, 
       typename std::enable_if<!std::is_same<t, float>::value, int>::type = 0>
    void function1(float a, Type b) {
    }

    void function1(float a, float b) {
    }
};
Run Code Online (Sandbox Code Playgroud)


Bra*_*vic 8

您可以使用模板专业化:

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);
Run Code Online (Sandbox Code Playgroud)

---编辑---

如果你有很多常用功能,你可以这样做:

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");
Run Code Online (Sandbox Code Playgroud)