将这些模板转换为别名声明

Transforming these templates to Alias Declarations

本文关键字:别名 声明 转换      更新时间:2023-10-16

我有一些基于编译时常量的模板,如下所示:

const int SIG0 = 0;
template<int Sig>
struct SignalPrototype;
template<>
struct SignalPrototype<SIG0> {
  typedef std::function< void() > type;
};

当我试图将其转换为 C++11(我相信)别名声明时,我无法让它以任何形式或形式工作(只发布其中之一):

const int SIG0 = 0;
template<int Sig>
using SignalPrototype = std::function< void() >;
template<>
using SignalPrototype<SIG0> = std::function< void() >;

出现错误:expected unqualified-id before ‘using’我想它期望模板参数中有一些东西,但我不能放SIG0因为它不是一种类型。

笔记:我正在使用C++标准,最高可达 C++17,所以任何我不知道的新东西也值得赞赏。

另外,我不喜欢标题中的"这些",但我不知道它们的具体名称是什么。

这里有几件事是错误的。 const int SIG0 = 0;需要成为constexpr而不是const。而且您不能专门化别名模板。

您可以做的是将这两种方法结合起来,如下所示:

constexpr int SIG0 = 0;
template <int Sig> struct SignalPrototype;
template<> struct SignalPrototype<SIG0> {
  typedef std::function< void() > type;
};
template <int Sig>
using SignalPrototype_t = typename SignalPrototype<Sig>::type;