gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 17:10:39 24 4
gpt4 key购买 nike

假设我们有一个类:

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); ( float a, float b);

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

A<float> a;

编译错误:

member function redeclared.

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

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

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

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

最佳答案

您可以使用一些 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) {
}
};

关于c++ - 根据类模板参数,定义或不定义类中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10395707/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com