如何能够“min”类型在可变参数包中找到? [英] How can the "min" type be found in a variadic parameter pack?
问题描述
通过min类型,我的意思是比较所有根据编译时函数 less 的类型,例如 sizeof
By "min" type, I mean the type compared less than all according to a compile time function, eg sizeof
我有一个实施草案,将首先介绍,并参考我面临的两个问题:
I have a draft implementation, will present it first and refer to the two problems I'm facing:
#include <iostream>
#include <typeinfo>
#include <type_traits>
using namespace std;
// Unspecialized version
template<typename...Ts>
struct Tmin
{
using type = void;
};
template<typename T>
struct Tmin<T>
{
using type = T;
};
template<typename T1, typename T2, typename...Ts>
struct Tmin<T1, T2, Ts...>
{
using type = typename std::conditional<sizeof(T1) < sizeof(T2),
typename Tmin<T1, Ts...>::type, typename Tmin<T2, Ts...>::type
>::type;
};
int main()
{
cout << typeid(Tmin<float, int, double>::type).name() << endl;
return 0;
}
-
(emit
致命错误C1075
)。我使用任何非标准设施还是有一个更合适的方式来写上面的?
This does not work in VS2013 (emits
fatal error C1075
). Am I using any non standard facilities or is there a more conforming way to write the above ?
假设我想使用 sizeof
以外的方法来比较类型。有没有一个consice方式/良好的设计,以能够传递metafunctions作为比较器,并仍然保持使用 sizeof
?的默认行为(其中非指定,否则是) p>
Say I want to use means other than sizeof
to compare types. Is there a consice way / good design to be able to pass metafunctions as comparators and still maintain a default behaviour (where non specified otherwise that is) that would use sizeof
?
推荐答案
如果您想使用不同的谓词, p>
If you want to use different predicates, the following should work:
#include <type_traits>
#include <typeinfo>
#include <iostream>
template<template<typename,typename> class P, typename... Ts>
struct min_t_impl;
template<template<typename,typename> class P, typename T>
struct min_t_impl< P, T >
{
using type = T;
};
template<template<typename,typename> class P, typename T, typename U, typename... Ts>
struct min_t_impl< P, T, U, Ts... >
{
using V = typename std::conditional< P<T,U>::value, T, U >::type;
using type = typename min_t_impl< P, V, Ts... >::type;
};
template<template<typename,typename> class P, typename... Ts>
using min_t = typename min_t_impl<P,Ts...>::type;
template<typename T,typename U>
using my_pred = std::integral_constant< bool, ( sizeof(T) <= sizeof(U) ) >;
int main()
{
std::cout << typeid(min_t<my_pred, float, int, double>).name() << std::endl;
return 0;
}
请注意,如何。四种类型和您的版本的示例可能产生所有以下实例化:
Note that you need to be careful with how you recurse. Example for four type and your version might yield all of the following instantiations:
Tmin<A,B,C,D>
Tmin<A,C,D>
Tmin<B,C,D>
Tmin<A,D>
Tmin<C,D>
Tmin<B,D>
Tmin<A>
Tmin<B>
Tmin<C>
Tmin<D>
而我是线性的,只能产生四个实例。您添加的参数越多,变得越重要!
while mine is linear and only yields four instantiations total. The more arguments you add, the more important this becomes!
这篇关于如何能够“min”类型在可变参数包中找到?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!