问题
i want a Base
template class with 2 template parameters. Specially, second parameter is a template parameter. Derived
is derived from Base
with CRTP. Now i want to generate the base class of Derived
like Base<Derived,Derived::second_tmpl>
, but the generating base class isn't same as the real base class of Derived
. How do i transmit a template?
#include <type_traits>
template<typename T, template<typename>class U>
struct Base
{
using type = Base<T,U>;
using devired_type = T;
template<typename V>
using second_tmpl = U<V>;
using second_type = second_tmpl<type>;
};
template<typename T>
struct Template
{
using type = Template<T>;
};
struct Derived
:public Base<Derived,Template>
{
};
//true
static_assert(
std::is_same<
Derived::second_type,
Template<Base<Derived,Template>>>::value,
"false");
//false
static_assert(
std::is_base_of<
Base<Derived,Derived::second_tmpl>,
Derived
>::value,
"false");
template<typename T>
using Template2 = Template<T>;
//false
static_assert(
std::is_same<
Base<Derived,Template>,
Base<Derived,Template2>
>::value,
"false");
Use a template which is the same as the original template instead of the original template. The judgement is false;
回答1:
These are the limitations of tempalte template arguments.
Template template arguments are second-class citizens in C++ :(
The second assert should really read
static_assert(std::is_base_of<Base<Derived, Template>, Derived>::value, "false");
which would work.
To combat the problem with the third (the fact that you "can't typedef an open template"), make it a meta-function: e.g. with TemplateGen
in the below program:
Live On Coliru
#include <type_traits>
template <typename T, typename UGen>
struct Base {
using type = Base<T, typename UGen::template type<T> >;
using devired_type = T;
template <typename V> using second_tmpl = typename UGen::template type<T> ;
using second_type = second_tmpl<type>;
};
template <typename T>
struct Template {
using type = Template<T>;
};
struct TemplateGen {
template <typename T> using type = Template<T>;
};
struct Derived : public Base<Derived, TemplateGen> {
};
// true
static_assert(std::is_same<Derived::second_type, Template<Derived> >::value, "false");
// false
static_assert(std::is_base_of<Base<Derived, TemplateGen>, Derived>::value, "false");
using Template2 = TemplateGen;
// false
static_assert(std::is_same<Base<Derived, TemplateGen>, Base<Derived, Template2>>::value, "false");
int main(){}
来源:https://stackoverflow.com/questions/27108614/how-to-transmit-a-template