1

我知道,我可以将类模板作为模板参数传递,如下所示:

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是变量模板。

4

1 回答 1

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

于 2020-05-07T18:21:41.490 回答