我有一堂課
template<typename T, typename U>
class A {
T i;
}
我有一個 B 類,它應該使用與 A 類相同的型別
template<typename A_Type>
class B
: public A_Type
{
T j; // here I need a class member of the same type as the first type of A_Type (T from class A)
}
所以我需要類似的東西
template<typename A_Type<T, U>>
class B
: public A_Type
{
T j;
}
這種表示法顯然不起作用,但是否有適合我需要的表示法?
uj5u.com熱心網友回復:
您可以在以下位置提供成員別名A:
template<typename T, typename U>
class A {
T i;
using value_type = T;
};
template<typename A_Type>
class B
: public A_Type
{
typename A_Type::value_type;
};
或者使用特化來推斷引數的型別:
template<typename T, typename U>
class A {
T i;
using value_type = T;
};
template<typename A_Type>
class B : public A_Type {};
template <typename T,typename U>
class B<A<T,U>> : A<T,U> {
T j;
};
如評論中所述,請注意術語。使用正確的術語可以避免問題。也不A是B類。它們是類模板。并且成員別名應該是protected(或放置在單獨的 trait 中template <typename A> struct get_T_from_instantiation_of_A;)
uj5u.com熱心網友回復:
你不能通過那種型別嗎?
template<typename A_Type, typename T>
class B
: public A_Type
{
T j; // here I need a class member of the same type as the first type of A_Type (T from class A)
}
uj5u.com熱心網友回復:
您可以創建一些型別特征來提供幫助。
第一個測驗型別是否真的是A型別:
#include <type_traits>
template<class T>
struct is_A_type {
static std::false_type test(...);
template<template<class...> class U, class... V,
std::enable_if_t<std::is_same_v<U<V...>, A<V...>>, int> = 0>
static std::true_type test(const U<V...>&);
static constexpr bool value = decltype(test(std::declval<T>()))::value;
};
template<class T>
inline constexpr bool is_A_type_v = is_A_type<T>::value;
然后是獲取第一個模板引數型別的特征:
template<class T>
struct first_type {
static void test(...);
template<template<class...> class U, class F, class... V>
static auto test(const U<F, V...>&) -> F;
using type = decltype(test(std::declval<T>()));
};
template<class T>
using first_type_t = typename first_type<T>::type;
然后可以像這樣使用這些特征:
template<class A_Type>
class B : public A_Type {
static_assert(is_A_type_v<A_Type>, "A_Type must be an A type");
using T = first_type_t<A_Type>;
T j;
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/493792.html
上一篇:c 多載(流提取和插入)運算子函式作為成員函式?[復制]
下一篇:檢查向量是否通過頂點c
