gpt4 book ai didi

c++ - 我希望类模板只有在传递给模板的类型为int时才具有sort方法

转载 作者:行者123 更新时间:2023-12-03 07:07:02 25 4
gpt4 key购买 nike

首先,我知道这个问题已经回答了,但是我真的不知道该怎么做
我正在创建自己的 vector 类(出于学习目的),并且我希望它具有仅当传递给模板的类型为int时才进行编码的sort方法。

template<typename T>
class vector
{
T* _arr = new T[5]{ 0 };
size_t _size = 0;

public:
template<>
void sort<int>()
{
// whatever
}
};
看起来像那样吗?顺便说一句,我希望在类中定义该方法。
你会怎么做?

最佳答案

C++ 20为此具有漂亮的requires:

template <typename T>
class vector
{
T* _arr = new T[5]{ 0 };
size_t _size = 0;

public:
void sort() requires(std::is_same_v<T, int>)
{
// whatever
}
};
对于以前的版本,您必须使用SFINAE
template <typename T>
class vector
{
T* _arr = new T[5]{ 0 };
size_t _size = 0;

public:
template <typename Dep = T, std::enable_if_t<std::is_same_v<Dep, int>, int> = 0>
void sort()
{
// whatever
}
};
或特殊化(您可能必须创建额外的CRTP类以将特殊化限制为额外的方法):
template <typename T> class vector;

template <typename T> struct vector_sorter {};

template <typename T>
struct vector_sorter<int>
{
private:
vector<int>& self() { return static_cast<vector<int>&>(*this); }
public:
void sort()
{
// whatever
// use `self()` instead of `this` to access `vector<int>` members
// such as `self()._arr`, `self()._size`
}
};

template <typename T>
class vector : vector_sorter<T>
{
friend vector_sorter<T>;

T* _arr = new T[5]{ 0 };
size_t _size = 0;

public:
// ...
};

#if 0 // Or specialize the full class
template <>
class vector<int>
{
int* _arr = new int[5]{ 0 };
size_t _size = 0;

public:
void sort()
{
// whatever
}
};
#endif

关于c++ - 我希望类模板只有在传递给模板的类型为int时才具有sort方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64937258/

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