【问题标题】:How to pass a variable template as template argument [duplicate]如何将变量模板作为模板参数传递[重复]
【发布时间】:2020-05-07 17:52:32
【问题描述】:

我知道,我可以像这样将类模板作为模板参数传递:

template <template <class> class ClassTemplate>
void foo()
{
    ClassTemplate<int> x;
}

int main()
{
    foo<std::optional>();
}

但假设我有一个变量模板:

template <class T>
constexpr bool IsBig = sizeof(T) >= sizeof(void*);

如何将它作为模板参数传递?有简单的解决方案吗?我猜该语言根本不支持它。这不起作用:

template <template <class> bool VariableTemplate>         // fictional C++ syntax
void foo()
{
    bool b = VariableTemplate<int>;
}

int main()
{
    foo<IsBig>();
}

标准化委员会是否正在努力将上述语法(或类似语法)作为新功能纳入 C++?

我没有找到简单的解决方案。我想这就是为什么所有类型特征目前都由 STL 中的一个类(具有...::type...::value 成员)表示。我想避免使用类作为特征。例如,实现IsBig 的直接方法是变量模板。

【问题讨论】:

  • 您的问题是“标准不允许这样做吗?”还是“有计划添加此功能吗?”?
  • @cigien:我的问题是后者:是否有持续努力/计划将此功能或类似功能添加到语言中?

标签: c++ variable-templates


【解决方案1】:

您不能直接使用变量模板执行此操作,但有一个简单的解决方法:

template<class T>
constexpr bool IsBig = sizeof(T) >= sizeof(void*);

template<class T>
struct IsBigWrapperA {
    static constexpr auto value = IsBig<T>;

    constexpr operator decltype(value)() const {
        return value;
    }
};

template <template<class> class VariableTemplateWrapper>
void foo() {
    bool b = VariableTemplateWrapper<int>();
}

int main() {
    foo<IsBigWrapperA>();
}

然后我们可以有一个宏(是的......)来允许一个通用的变量模板包装器

#define CREATE_WRAPPER_FOR(VAR)                    \
  template<typename T>                             \
  struct VAR##Wrapper {                            \
      static constexpr auto value = VAR<T>;        \
      constexpr operator decltype(value)() const { \
          return value;                            \
      }                                            \
  };

// need to call the macro to create the wrapper
CREATE_WRAPPER_FOR(IsBig)

template<template<class> class VariableTemplateWrapper>
void foo() {
    bool b = VariableTemplateWrapper<int>();
}

int main() {
    foo<IsBigWrapper>();
}

代码:https://godbolt.org/z/gNgGhq

【讨论】:

  • 谢谢。我知道了。你概括了这个想法。在bool 的情况下,我们可以使用std::bool_constant (example) 进行简化,但如果变量模板是任何文字类型,则不能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-23
  • 2011-09-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多