【问题标题】:Can the type of partial specialization be inferred?可以推断出偏特化的类型吗?
【发布时间】:2021-10-17 07:01:12
【问题描述】:

我正在设计一系列向量来支持一些数学运算,部分内容如下

enum class precision
{
    high,
    medium,
    low,

    default_precision = high
};

template<typename T>
concept arithmetic = std::is_integral_v<T> || std::is_floating_point_v<T>;

using vector_size_type = std::size_t;
using matrix_size_type = std::size_t;
template<vector_size_type Size, arithmetic T, precision = precision::default_precision>
struct vector;

template<arithmetic T, precision P = precision::default_precision>
using vector1 = vector<1, T, P>;

template <arithmetic T, precision P>
struct vector<1, T, P>
{
    template <vector_size_type Size, arithmetic U>
    using acceptable_type = vector<Size, U, P>;

    using container_type = std::array<T, 1>;
    using value_type = typename container_type::value_type;
    using size_type = typename container_type::size_type;
    
    constexpr static size_type data_index = 0;
    constexpr static size_type data_size = 1;

    constexpr          vector() noexcept = default;

    constexpr explicit vector(value_type scalar) noexcept : data_({scalar}) {}
    
    template<arithmetic U>
    constexpr explicit vector(U scalar) noexcept(std::is_nothrow_convertible_v<U, value_type>) : data_({static_cast<value_type>(scalar)}) {}

    template<vector_size_type Size>
    requires (Size >= data_size)
    constexpr explicit vector(const acceptable_type<Size, value_type>& other) noexcept
        : data_({other[data_index]}) {}
    
    template <vector_size_type Size, typename U>
        requires (Size >= data_size)
    constexpr explicit vector(const acceptable_type<Size, U>& other) noexcept(std::is_nothrow_convertible_v<U, value_type>)
        : data_({static_cast<value_type>(other[data_index])}) {}

private:
    container_type data_;
};
//===========================================
// test
//==========================================
// OK
constexpr vector1<int> vec1{ 10 };
constexpr vector1<long> vec2{ -10 };

// missing parameter list for template alias vector1

// vector1 vec3{3.14};

// the template alias vector1 has too few parameters

// vector1<> vec4{1234};

如何让vector1具备类型推断的功能?或者可以推断出偏特化的类型?

https://gcc.godbolt.org/z/W7nG4nGnh

【问题讨论】:

标签: c++ templates c++20 type-inference


【解决方案1】:
  1. 您需要以}; 而不是} 结束struct vector
  2. 没必要,不过用size_t代替size_type比较常见,不过还是一样的东西。
  3. 您为什么使用size_type?为什么不直接使用int。

【讨论】:

  • 从size_type 更改为int 为我修复了所有错误。
  • 我收到更多错误:gcc.godbolt.org/z/4qz5hvcWc
  • 我的所有测试都通过以确保代码正确,唯一的问题是我希望能够推断出类型。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-13
  • 1970-01-01
相关资源
最近更新 更多