static_assert - PullRequest
       18

static_assert

3 голосов
/ 15 июня 2019

Я создаю шаблонный Matrix класс, и я ограничил параметры шаблона целыми и плавающими точечными типами данных

template class Matrix<int>;
template class Matrix<float>; ..etc

Я реализовывал random() статическую функцию-член, и чтобы сделать ее равномерным случайным распределением от 0.0 до 1.0, я использовал std::is_floating_point<T>, чтобы ограничить использование шаблонов плавающих типов точек.и я думал, что static_assert сработает, если только T не является типом с плавающей запятой, но утверждение не выполняется для каждого template class Matrix<T>;, где T является целочисленным типом.

Когда я закомментирую все целочисленные типы, он работает нормально, но я не могу этого сделать, поскольку мне нужно иметь возможность создавать Matrix<T> экземпляров с T, это интегральный тип.Как бы это исправить?

Обратите внимание, что я предоставил template class Matrix<T> для каждого целочисленного / плавающего -точечного типа, потому что я получаю ошибку undefined reference.Поэтому я ограничиваю инициализацию целочисленными и плавающими точечными типами.

// Matrix.cpp
template<typename T>
Matrix<T> Matrix<T>::rand(const size_t& r, const size_t& c) {
    Matrix<T> result{ r, c };
    static_assert(std::is_floating_point<T>::value,
        "result_type must be a floating point type");
    const float range_from = 0.0;
    const float range_to = 1.0;
    std::random_device                  rand_dev;
    std::mt19937                        generator(rand_dev());
    std::uniform_real_distribution<T>   distr(range_from, range_to);
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            result[i][j] = distr(generator);
        }
    }
    return result;
}
//...
template class Matrix<int>;
template class Matrix<long>;
template class Matrix<float>;
template class Matrix<double>;

Ответы [ 2 ]

3 голосов
/ 15 июня 2019

У вас есть несколько вариантов:

  • предоставить (шаблон) код в заголовке вместо cpp (см. почему только шаблоны могут быть реализованы в заголовочном файле )
  • явно экземпляры методов вместо класса:

    // all individual available methods of the class
    template Matrix<int> Matrix<int>::other_method(/*..*/); 
    // ...
    
    // Whole class
    template class Matrix<float>;
    template class Matrix<double>;
    
  • Использовать SFINAE:

    template<typename T>
    class Matrix
    {
        template <typename U = T,
                  std::enable_if_t<std::is_same<T, U>::value
                                   && std::is_floating_point<U>::value, int> = 0>
        Matrix<T> rand(const size_t &r, const size_t &c);
    // ...
    };
    
  • или requires из C ++ 20:

    template<typename T>
    class Matrix
    {
        Matrix<T> rand(const size_t &r, const size_t &c) requires (std::is_floating_point<T>::value);
    // ...
    };
    
  • или специализированный класс

    template<typename T, typename Enabler = void>
    class Matrix
    {
    // ...
    };
    
    template<typename T>
    class Matrix<T, std::enable_if_t<std::is_floating_point<T>::value>>
    {
        Matrix<T> rand(const size_t &r, const size_t &c);
    // ...
    };
    
2 голосов
/ 15 июня 2019

Когда я закомментирую все целочисленный тип с, он работает нормально, но я не могу сделать это как я должен иметь возможность сделать Matrix<T> экземпляров с T является целочисленный тип e. Как бы это исправить?

Как указывалось в комментариях @ Jarod42 , вы можете применить SFINAE , чтобы ограничить использование функции rand() тогда и только тогда, когда шаблон тип с плавающей запятой.

Бонусное замечание: ту же технику можно применить для ограничения создания экземпляра класса Matrix<T> путем создания экземпляра класса условно для разрешенных типов, упомянутых в чертах.

Ниже приведен пример кода (компилируется с ), который демонстрирует эту идею.

( см. Онлайн )

#include <iostream>
#include <type_traits> // for std::conjunction, std::negation, std::is_arithmetic, std::is_floating_point, std::enable_if

// traits for filtering out the allowed types
template<typename Type>
using is_allowed = std::conjunction<
    std::is_arithmetic<Type>,    // is equal to  std::is_integral_v<T> || std::is_floating_point_v<T>>
    std::negation<std::is_same<Type, bool>>,    // negate the types which shouldn't be compiled
    std::negation<std::is_same<Type, char>>,
    std::negation<std::is_same<Type, char16_t>>,
    std::negation<std::is_same<Type, char32_t>>,
    std::negation<std::is_same<Type, wchar_t>>
>;

template<typename Type, typename ReType = void>
using is_allowed_type = std::enable_if_t<is_allowed<Type>::value, ReType>;

template<typename Type, typename Enable = void> class Matrix;
// conditional instantiation of the template class
template<typename Type> class Matrix<Type, is_allowed_type<Type>> /* final */
{
public:
    template<typename T = Type>
    std::enable_if_t<std::is_floating_point_v<T>, Matrix<T>> rand(const size_t& r, const size_t& c)
   //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ SFINAE to restrict the use of rand()
    {
        Matrix<T> result{/*args*/};
        // other code
        return result;
    }
};
template class Matrix<int>;
template class Matrix<long>;
template class Matrix<float>;

int main()
{
   Matrix<double> obj;
   obj.rand(1, 2);
}
...