【问题标题】:Static member initialization and variadic template静态成员初始化和可变参数模板
【发布时间】:2015-11-08 21:24:11
【问题描述】:

通过查看以下代码,我们注意到初始化名为cnt 的静态数据成员非常容易:

template<typename T> struct Base { static int cnt; };
template<typename T> int Base<T>::cnt = 0;
int main() { }

无论如何,我正在努力处理variadic_template 和静态数据成员,因为我无法使用它们。考虑以下代码:

template<typename...> struct Base;
template<> struct Base<> { static int cnt; };
int main() { }

首先,我尝试了最明显的事情,至少是对我来说最明显的事情:

template<typename... T> int Base<T...>::cnt = 0;

它返回了error: template definition of non-template ‘int Base&lt;T&gt;::cnt’,我立即意识到我的尝试确实没有意义。话虽如此,之后我有点困惑,因为我不再清楚哪种语法是正确的。

我尝试了以下几种:

template<> int Base<>::cnt = 0;
// ... and ...
template<> int Base::cnt = 0;

出现错误error: template definition of non-template ‘unsigned int Base&lt;T&gt;::cnt’error: ‘template&lt;class ... T&gt; struct Base’ used without template parameters

到目前为止,我已经与variadic templates 合作了一些,但我不知道如何与他们合作。我什至无法弄清楚这是否可能,也不知道哪种语法是正确的。

任何帮助将不胜感激。

【问题讨论】:

    标签: c++ templates c++11 static-members static-initialization


    【解决方案1】:

    只使用

    int Base<>::cnt = 42;
    

    此时,Base&lt;&gt; 是一个完整的专业化,你不专业化任何东西,所以template&lt;&gt; 不再需要,实际上是被禁止的。

    【讨论】:

    • @skypjack 没什么好羞愧的 ;) 模板语法是 C++ 中最黑暗的部分之一。
    • 是的,我同意你的观点,但这很明显!! :-)
    【解决方案2】:

    只需将其初始化为:

    int Base&lt;&gt;::cnt = 0;

    LIVE DEMO

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-02
      • 2016-03-10
      • 1970-01-01
      相关资源
      最近更新 更多