The*_*isp 7 c++ metaprogramming template-meta-programming constexpr c++11
最近我设计了元类型和允许编译时类型连接的可能操作:
#include <tuple>
template<template<typename...> typename T>
struct MetaTypeTag
{};
/*variable template helper*/
template<template<typename...> typename T>
constexpr MetaTypeTag<T> meta_type_tag = {};
template<typename T>
struct TypeTag
{};
/*comparison*/
template<typename T>
constexpr bool operator==(TypeTag<T>, TypeTag<T>) { return true; }
template<typename T, typename U>
constexpr bool operator==(TypeTag<T>, TypeTag<U>) { return false; }
/*variable template helper*/
template<typename T>
constexpr TypeTag<T> type_tag = {};
template<template<typename...> typename T, typename... Ts>
constexpr TypeTag<T<Ts...>> combine(MetaTypeTag<T>, TypeTag<Ts>...)
{
return {};
}
int main()
{
constexpr auto combined_tag = combine(meta_type_tag<std::tuple>, type_tag<int>, type_tag<float>);
static_assert(combined_tag == type_tag<std::tuple<int, float>>, "");
}
Run Code Online (Sandbox Code Playgroud)
在std::tuple没有模板参数不能用作类型,但仍可能出现在模板的模板参数.
现在,如果我们试图走一步,问题是,是否有什么办法,以统一struct MetaTypeTag和struct TypeTag,因为它们都是空的班级,一个模板参数,或者至少也可能是有可能使用相同的变量的模板type_tag,但重定向到一个不同的类别取决于类型类别?所以我会想象这样的事情:
template<???>
constexpr auto type_tag = ????{};
//use with 'incomplete type'
type_tag<std::tuple> //MetaTypeTag<std::tuple>
//use with regular type
type_tag<int> //TypeTag<int>
Run Code Online (Sandbox Code Playgroud)
我尝试了所有可能的方法 - 重新定义,显式特化,部分特化,可选模板参数,条件使用别名,但没有工作.我曾希望C++ 17 template<auto>会有所帮助,但事实证明一个只适用于非类型.
问题是是否有任何方法可以统一
struct MetaTypeTag和struct TypeTag,因为它们都是具有一个模板参数的空类
我不这么认为。我能想象的最好的方法是简化一点(非常一点)你的代码是定义几个重载constexpr函数,比如说getTag()
template <typename T>
auto constexpr getTag ()
{ return TypeTag<T>{}; }
template <template <typename ...> typename T>
auto constexpr getTag ()
{ return MetaTypeTag<T>{}; }
Run Code Online (Sandbox Code Playgroud)
所以你可以调用getTag<T>()whereT是类型或模板。
所以你可以combine()这样调用
constexpr auto combined_tag
= combine(getTag<std::tuple>(), getTag<int>(), getTag<float>());
Run Code Online (Sandbox Code Playgroud)
但我不认为这是一个很大的进步。