J. *_*Doe 5 c++ templates c++11 type-alias c++17
假设我有一个模板:
template<typename T>
struct Outer {
template<typename T1>
struct Inner {
};
};
Run Code Online (Sandbox Code Playgroud)
我想要一个别名模板Alias:
template<typename T>
using Alias = Outer<T>::template Inner; // this won't work
using IntOuter = Alias<int>;
Run Code Online (Sandbox Code Playgroud)
因此IntOuter<double>与Outer<int>::template Inner<double>。您如何定义Alias?还是可能吗?
编辑:
我希望能够SomeOuter即时创建模板foo:
template<template<typename> class>
struct Foo {
};
Run Code Online (Sandbox Code Playgroud)
Foo<Alias<int>> 与...相同 Foo<Outer<int>::template Inner>
或做这样的事情:
template<typename T>
using SomeFoo = Foo<Alias<T>>;
Run Code Online (Sandbox Code Playgroud)
你不能做你所要求的事。
这就是你问题的答案。你问一个狭窄的问题,没有足够的背景,这是我能做的最好的事情。
如果您想在 C++ 中进行严格的元编程,您可以将模板转换为类型或值。请参阅 boost hana 库了解一种方法。
但没有人会与之互动
template<template<typename> class>
struct Foo {
};
Run Code Online (Sandbox Code Playgroud)
“盒子外面”。
template<class T>struct tag_t{using type=T;};
template<class T>constexpr tag_t<T> tag{};
template<template<class...>class Z>struct ztemplate_t{
template<class...Ts>using apply=Z<Ts...>;
template<class...Ts>
constexpr tag_t<Z<Ts...>> operator()(tag_t<Ts>...)const{return {};}
};
template<template<class...>class Z>constexpr ztemplate_t<Z> ztemplate{};
template<class Tag>using type_t=typename Tag::type;
#define TYPE(...) type_t<decltype(__VA_ARGS__)>
Run Code Online (Sandbox Code Playgroud)
现在
template<typename T>
constexpr auto Alias = ztemplate<Outer<T>::template Inner>;
Run Code Online (Sandbox Code Playgroud)
现在是一个类似于模板的值。
映射Foo到:
template<template<class...>class Z>
constexpr tag_t<Foo<Z>> foo( ztemplate_t<Z> ){return {};}
Run Code Online (Sandbox Code Playgroud)
让你做TYPE( foo(Alias( tag<int> ) ) )。
这可能不是您想要的。