请考虑以下代码片段:
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_type
在 E
中指定每当E
是 vector_expression
.上面的代码不起作用,导致模板参数 E
在 value_type
的部分特化中不可推导.我怎样才能使代码工作?
最佳答案
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;
};
关于c++ - 我的部分模板特化的模板参数不可推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36522065/