C++:比较变量无符号int模板参数的助手
在一个混合了CRTP、可变模板、元编程和运算符重载的类中,我想比较两个可变无符号int模板参数,以便进行一些静态断言。我认为helper结构将是一种很好的方法,但我不知道如何做到这一点。我想到了一些形式:C++:比较变量无符号int模板参数的助手,c++,c++11,helpers,variadic-templates,C++,C++11,Helpers,Variadic Templates,在一个混合了CRTP、可变模板、元编程和运算符重载的类中,我想比较两个可变无符号int模板参数,以便进行一些静态断言。我认为helper结构将是一种很好的方法,但我不知道如何做到这一点。我想到了一些形式: template<unsigned int... TDIM, unsigned int... TDIM0> struct HelperCheckDimensions { static const bool ok = /* SOMETHING */ }; 我希望只有当siz
template<unsigned int... TDIM, unsigned int... TDIM0> struct HelperCheckDimensions
{
static const bool ok = /* SOMETHING */
};
我希望只有当sizeof…TDIM==sizeof…TDIM0和TDIM[0]==TDIM0[0],TDIM[1]==TDIM0[1],…,TDIM[n]==TDIM0[n]时,结果才是真的
怎么做
非常感谢。我想说,这种形式的类变量模板没有意义:
template<unsigned int... TDIM, unsigned int... TDIM0>
struct HelperCheckDimensions
{
//..
};
或者这是正确的:
TDIM = (1,2)
TDIM0 = (3,4,5,6)
TDIM = (1)
TDIM0 = (2,3,4,5,6)
或者这个:
TDIM = (1,2,3,4)
TDIM0 = (5,6)
希望这有助于解释为什么它没有意义
根据您的评论:
很好的观点!但我的问题仍然悬而未决。。。也许表单模板中的某些东西会起作用?最好的解决方案是什么 标准不允许使用此表单的模板定义:
template<unsigned int... TDIM, typename TFAKE, unsigned int... TDIM0>
我不知道为什么标准不允许它,即使它对我来说是有意义的,至少在这种情况下,它可能会给语言增加不值得的复杂性。根据该标准,模板参数包必须是模板定义的最后一个参数
如果在GCC中编译上述代码,则会出现以下错误:
错误:参数包“TDIM”必须位于模板参数列表的末尾
希望对您有所帮助。主类模板不能有两个参数包,您需要使用一些包包装器
template<unsigned int...T> struct intPack;
template<typename T, typename Y> struct HelperCheckDimensions;
template<unsigned int lhs, unsigned int...T, unsigned int rhs, unsigned int...Y> struct HelperCheckDimensions<intPack<lhs,T...>, intPack<rhs, Y...>>
{
static const bool value = lhs==rhs && HelperCheckDimensions<intPack<T...>, intPack<Y...>>::value;
};
template<unsigned int lhs, unsigned int rhs> struct HelperCheckDimensions<intPack<lhs>, intPack<rhs>>
{
static const bool value = lhs==rhs;
};
测试:假设您的主模板如下所示:
template <int ...> struct Foo;
用法:
typedef Foo<1, 3, 4> F1;
typedef Foo<9, 5, 1> F2;
template <typename S, typename T>
std::enable_if<FooCmp<S, T>::value> do_magic(S s, T t) { /* ... */ }
do_magic(F1{}, F2{});
很好的观点!但我的问题仍然悬而未决。。。也许表单模板中的某些东西会起作用?最好的解决方案是什么?我认为他们不允许这样做,部分原因是这可能导致了他们当时无法想到的错误。从某种意义上说,这是一种安全感,如果他们认为真的没有问题,那么以后可能会提升。这不是第一次/是否允许:模板?GCC表示,参数包必须位于模板参数的末尾list@Nawaz这是有效的,因为包以部分形式出现specialization@Mr.Anubis当前位置使用包装,唯一明智的做法是打开包装并将其视为头部加尾部。
template <int ...> struct Foo;
template <typename, typename> struct FooCmp : std::false_type { };
template <int A, int B, int ...As, int ...Bs>
struct FooCmp<Foo<A, As...>, Foo<B, Bs...>>
: std::integral_constant<bool, A == B && FooCmp<Foo<As...>, Foo<Bs...>>::value>
{ };
template <> struct FooCmp<Foo<>, Foo<>> : std::true_type { };
typedef Foo<1, 3, 4> F1;
typedef Foo<9, 5, 1> F2;
template <typename S, typename T>
std::enable_if<FooCmp<S, T>::value> do_magic(S s, T t) { /* ... */ }
do_magic(F1{}, F2{});