9

假设我们有一个类:

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

现在像这样实例化类:

A<int> a;

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

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

A<float> a;

你得到编译错误:

成员函数重新声明。

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

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

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

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

4

3 回答 3

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) {
    }
};
于 2012-05-01T09:46:00.567 回答
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);

- - 编辑 - -

如果你有大量的常用函数,你可以这样做:

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");
于 2012-05-01T09:22:17.337 回答
2

使用 SFINAE:

#include <iostream>
#include <type_traits>

template <typename Type>
struct Foo {
    template <typename T = Type>
    void function1(float a, float b, typename std::enable_if<!std::is_same<T, float>::value>::type *c = 0) {
        std::cout << "float\n";
    }
    void function1(float a, Type b) {
       std::cout << "type\n";
    }
};

int main() {
    Foo<float> f;
    f.function1(1, 1);
    f.function1(1.0f,1.0f);
    Foo<int> g;
    g.function1(1,1);
    g.function1(1.0f,1.0f);
    g.function1(1.0,1.0); // warning!
}

输出:

type
type
type
float
type

您需要 C++11 模式,以允许函数模板中的默认模板参数。也可以得到enable_ifand is_same,尽管你可以enable_if从 Boost 中得到。

“警告!” 是因为你的原始代码g.function1(1.0,1.0);是模棱两可的。现在首选非模板重载。您可以通过这样做再次使其模棱两可

    template <typename T = Type>
    void function1(float a, Type b, typename std::enable_if<true>::type *c = 0) {
       std::cout << "type\n";
    }
于 2012-05-01T10:09:38.153 回答