如何将变量模板作为模板参数传递

时间:2020-05-07 17:52:32

标签: c++ variable-templates

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

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的直接方法是变量模板。

1 个答案:

答案 0 :(得分: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