[英]variadic template struct, recursive type declaration, is it possible?
there!那里!
There is any way to declare a type recursively?有没有办法递归地声明一个类型? I was almost there but I got a compile error.
我快到了,但出现编译错误。
I'm designing a simple template to determine the optimal type for storing the result of operating mixed type stuff.我正在设计一个简单的模板来确定用于存储操作混合类型内容的结果的最佳类型。
OP_T<> Use case example: OP_T<> 用例示例:
typename OP_T<char, float, int>::M var //var is actually a float
Code代码
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'
};
This is x_traits simplified这是简化的 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> {};
Here you can find a more detailed use case example (but still simplified): https://godbolt.org/z/jbcahq在这里您可以找到更详细的用例示例(但仍然简化): https : //godbolt.org/z/jbcahq
I guess you meant something like this:我猜你的意思是这样的:
template <typename T0, typename... Ts>
struct OP_T<T0, Ts...> {
using M = typename OP_T<T0, typename OP_T<Ts...>::M>::M;
};
Now OP_T<T1, T2, ...>::M
will be a type obtained from the pack T1, T2, ...
by the application of the "reduction" binary metafunction x_traits<S, T>::MULT_T
, similar in spirit to what std::accumulate
with a custom binary operation does.现在
OP_T<T1, T2, ...>::M
将是通过应用“归约”二进制元函数x_traits<S, T>::MULT_T
从包T1, T2, ...
获得的类型,类似本质上是std::accumulate
与自定义二元运算的作用。
I suspect thatSince you need result type of some chained operation this could look like this (using 我怀疑
C++17
fold expression):由于您需要某些链式操作的结果类型,因此可能如下所示(使用
C++17
折叠表达式):
template<typename ...Ts>
using mutiplication_result_t = decltype((std::declval<Ts>() * ...));
Same for C++11:与 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.