由this question触发,我编写了一个模板,允许将模板转换为具有不同参数的模板:
template< template <int A,char B,bool> typename T>
struct Add_true {
template <int A,char B> using type = T<A,B,true>;
};背景:目的是将template<int A, char B, bool C> class A2{};作为模板模板参数传递给template<template<int A, char B> typename T> class A1 {};。我用C++11学习了模板,当我习惯于编写接受类型和“返回”类型的类型/函数,而不是编写采用值和返回值的函数时,代码的思想发生了很大的转变。我从来没有想到,编写给模板“返回”不同模板的模板也是令人惊讶的简单。问题是,我一点也不知道如何在没有别名模板的情况下编写上面的或类似的模板,这些模板只有在C++11之后才可用。给定的
template <int A,char B, bool C> struct Foo{};我可以通过以下方式将bool参数“绑定”到Foo:
template <int A,char B>
struct Add_true_to_Foo {
typedef Foo<A,B> type;
};但是现在Add_true_to_Foo<A,B>::type不是一个模板,没有C++11,我一点也不知道如何编写一个Add_true,它不仅适用于Foo,而且也适用于
template <int A,char B, bool C> struct Bar{};也许我错过了一些显而易见的东西。我的问题是
是否可以在Add_true?之前编写与上述相当的代码?
发布于 2020-02-20 10:45:59
使用的C++11模板没有严格的等效项,但是可以添加额外的模板类,以模仿行为,并使用不同的语法:
template <template <int, char, bool> class C>
struct Add_true {
template <int A, char B>
struct apply
{
typedef T<A, B, true> type;
}
};与用法:
template <int A,char B, bool C> struct Foo{};
typedef Add_true<Foo>::apply<42, '*'>::type my_type; // Foo<42, '*', true>发布于 2020-02-20 10:46:19
继承将是C++03的方式
template< template <int A,char B,bool> typename T>
struct Add_true {
template <int A,char B>
struct type : T<A,B,true> {};
};在C++11和C++03中,type都是新模板的名称。区别仅仅在于专业化意味着什么。对于别名模板,它们完全代表被别名的事物,而在这里,它们是新的类型。但是,派生到基本转换应该允许将C++03 type专门化处理得与它们“别名”几乎完全一样。
发布于 2020-02-20 10:53:04
在C++03中,我们没有模板别名,但是可以通过这样的结构模板来实现相同的目标:
template<template<int A, char B> class T> class A1
{
typedef typename T<1, 'a'>::type actual_A2;
};
template<int A, char B, bool C> class A2 {};
template< template<int A, char B, bool C> class T >
struct Add_true
{
template<int A, char B>
struct apply
{
typedef T<A, B, true> type;
};
};
typedef Add_true<A2> A2_with_true;
A1< A2_with_true::apply > a1;请注意,您需要更改A1的工作方式,因为它必须使用嵌套的type类型类型来获得实际的A2专门化。
https://stackoverflow.com/questions/60318020
复制相似问题