【问题标题】:Q: Template class that takes either a normal type or a template template argument问:接受普通类型或模板模板参数的模板类
【发布时间】:2018-01-29 19:53:17
【问题描述】:

最近我设计了元类型和允许编译时类型连接的可能操作:

#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>>, "");
}

不带模板参数的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>

我尝试了所有可能的方法 - 重新定义、显式特化、部分特化、可选模板参数、有条件地使用别名,但都没有奏效。我曾希望 C++17 的 template&lt;auto&gt; 会有所帮助,但事实证明它仅适用于非类型。

【问题讨论】:

  • 当您说“统一”MetaTypeTag 和 TypeTag 时,您究竟是什么意思?能否举例说明您希望实现的目标?
  • 已编辑。我的意思是要么通过使用相同的模板类,要么使用相同的表达式来获得不同的行为。一开始我以为这可以通过专业化来解决,但我错了。

标签: c++ c++11 metaprogramming template-meta-programming constexpr


【解决方案1】:

问题是有没有办法统一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>{}; }

因此您可以调用getTag&lt;T&gt;(),其中T 是类型或模板。

所以你可以拨打combine()如下

constexpr auto combined_tag
   = combine(getTag<std::tuple>(), getTag<int>(), getTag<float>());

但我不认为这是一个很大的改进。

【讨论】:

    猜你喜欢
    • 2014-01-29
    • 2022-07-19
    • 2019-11-22
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多