【问题标题】:what's the diff between these two calls of static template class member function?这两个静态模板类成员函数调用之间有什么区别?
【发布时间】:2018-03-30 03:40:23
【问题描述】:

我正在尝试使用非类型模板参数,但遇到了我无法理解的编译器错误,更不用说解决了。

我希望我的模板类的成员之一是静态的。无论出于何种原因,我都可以从main() 中成功调用静态类成员函数,但不能在它之前调用,如下所示:

enum class PrimeBits {
    Two = 2,
    Three = 2,
    Five = 3,
    Seven = 3,
    Eleven = 4
};

template <typename T, enum PrimeBits P>
class wibble {
    public:

        wibble() {};

        static void nBits () {
            std::cout << "Bits: " << static_cast<int>(P) << std::endl;
        }
};

wibble<int, PrimeBits::Eleven>::nBits();        // compiler error
// specializing member 'wibble<int, (PrimeBits)4>::nBits' requires 'template<>' syntax

int main () {

    wibble<int, PrimeBits::Eleven>::nBits();        // compiles & runs ok 

}

这是带有 -std=gnu++17 集的 gcc 版本 7.3.0。

【问题讨论】:

  • 你不能从全局范围内调用任何东西(除了初始化全局变量)。
  • 谢谢!我想将我的问题重新表述为“为什么这个编译器错误消息如此无用?”

标签: c++ templates c++17 non-type


【解决方案1】:

如果你想在main之前调用方法,你可以使用全局变量: 由于您的方法返回void,使用逗号运算符能够初始化一个变量:

static const auto dummy = (wibble<int, PrimeBits::Eleven>::nBits(), 0);

【讨论】:

  • 谢谢。这是狡猾的解决方法代码。我认为 CurlyBracket 提供了我要打勾的答案。
猜你喜欢
  • 2023-01-10
  • 2017-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多