[英]variadic template struct, recursive type declaration, is it possible?
那里!
有沒有辦法遞歸地聲明一個類型? 我快到了,但出現編譯錯誤。
我正在設計一個簡單的模板來確定用於存儲操作混合類型內容的結果的最佳類型。
OP_T<> 用例示例:
typename OP_T<char, float, int>::M var //var is actually a float
代碼
template <typename ...T>
struct OP_T{};
template <typename T0, typename T1>
struct OP_T<T0, T1> {
using M = typename x_traits<T0, T1>::MULT_T;
};
template <typename T0, typename ...Ts>
struct OP_T<T0, Ts...> {
using M = typename OP_T<T0, Ts...>::M; // error: 'M' is not a member of 'OP_T'
};
這是簡化的 x_traits
template<typename T>
struct x_traits_default {
typedef T MULT_T;
};
template<typename T1, typename T2>
struct x_traits {};
template<typename T2>
struct x_traits<double, T2> : public x_traits_default<double> {};
template<typename T1>
struct x_traits<T1, double> : public x_traits_default<double> {};
在這里您可以找到更詳細的用例示例(但仍然簡化): https : //godbolt.org/z/jbcahq
我猜你的意思是這樣的:
template <typename T0, typename... Ts>
struct OP_T<T0, Ts...> {
using M = typename OP_T<T0, typename OP_T<Ts...>::M>::M;
};
現在OP_T<T1, T2, ...>::M
將是通過應用“歸約”二進制元函數x_traits<S, T>::MULT_T
從包T1, T2, ...
獲得的類型,類似本質上是std::accumulate
與自定義二元運算的作用。
我懷疑由於您需要某些鏈式操作的結果類型,因此可能如下所示(使用C++17
折疊表達式):
template<typename ...Ts>
using mutiplication_result_t = decltype((std::declval<Ts>() * ...));
與 C++11 相同:
template<typename T1, typename ...Ts>
struct mutiplication_result
{
using type = decltype(std::declval<T1>() * std::declval<typename mutiplication_result<Ts ...>::type>());
};
template<typename T>
struct mutiplication_result<T>
{
using type = typename std::decay<T>::type;
};
template<typename ...Ts>
using mutiplication_result_t = typename mutiplication_result<Ts...>::type;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.