c++ - 我的部分模板特化的模板参数不可推导

标签 c++ templates template-specialization typetraits c++17

请考虑以下代码片段:

template<class E>
class vector_expression {};

template<class Tuple>
class vector
    : public vector_expression<vector<Tuple>>
{
public:
    using value_type = typename Tuple::value_type;
};

template<typename T>
using dynamic_vector = vector<std::vector<T>>;

namespace detail
{
    template<class E>
    constexpr bool is_vector_expression_v = std::is_base_of_v<vector_expression<std::decay_t<E>>, std::decay_t<E>>;

    template<class E>
    struct value_type { using type = std::decay_t<E>; };
    template<class E>
    struct value_type<vector_expression<std::decay_t<E>>> { using type = typename std::decay_t<E>::value_type; };
    template<class E>
    using value_type_t = typename value_type<E>::type;
}


int main()
{
    static_assert(std::is_same<detail::value_type_t<dynamic_vector<double>>, double>::value, "not the same");   
    return 0;
}

我要value_type_t<E>成为value_typeE 中指定每当Evector_expression .上面的代码不起作用,导致模板参数 Evalue_type 的部分特化中不可推导.我怎样才能使代码工作?

DEMO

最佳答案

std::decay_t<E>不可推导,因为它实际上是std::decay<E>::type (实际上,在您的特定情况下,多个 E 可能导致相同的类型)。

需要第二次修复才能通过您的 static_assert :

作为dynamic_vector<double>不是 vector_expression但继承它,你的特化不匹配。您可以使用 SFINAE 来解决这个问题:

template<class E, typename Enabler = void>
struct value_type { using type = std::decay_t<E>; };

template<class E>
struct value_type<E, std::enable_if_t<is_vector_expression_v<E>>> {
    using type = typename std::decay_t<typename E::type>::value_type;
};

Demo

关于c++ - 我的部分模板特化的模板参数不可推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36522065/

相关文章:

c++ - 是否有可能获得指向通用 lambda 显式实例化的指针?

c++ - 模板化类中模板化成员函数的特化

C++ 模板特化语法

c++ - 如何检查功能模板是否已专门化?

c++ - getline 不等待输入

c++ - 从初始化列表分配给数组

c++ - 无法调用模板构造函数

c++ - 当对象类型是模板参数时,有没有办法将模板参数传递给对象上的函数?

c++ - std::map 标准分配器性能与 block 分配器

c++ - C/C++ - 条件头文件包含不起作用