我希望类模板只有在传递给模板的类型是 int 时才具有排序方法

Kar*_*los 1 c++

首先,我知道这个问题已经回答了,但我真的不明白该怎么做

我正在创建我自己的向量类(用于学习目的),并且我希望它有一个排序方法,只有当传递给模板的类型为 int 时,我才对其进行编码。

template<typename T>
class vector
{
    T* _arr = new T[5]{ 0 };
    size_t _size = 0;
    
public:
    template<>
    void sort<int>()
    {
        // whatever
    }
};
Run Code Online (Sandbox Code Playgroud)

它看起来像那样吗?顺便说一句,我希望在类中定义该方法。你会怎么做?

Jar*_*d42 6

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

对于以前的版本,您必须使用 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
    }
};
Run Code Online (Sandbox Code Playgroud)

或专业化(您可能必须创建额外的 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
Run Code Online (Sandbox Code Playgroud)