首页 > 解决方案 > Clang 无法初始化静态 const 模板成员

问题描述

为了在程序启动时强制执行模板方法,可以使用静态方法初始化静态成员。然后该方法在模板类的每个实例化的程序开始时运行:

#include <cstdio>


template<typename t, t value>
struct dummy_user_t {};

template<int i>
struct my_struct_t
{
    static int s_value;

    // "use" s_value so it's initialized
    using value_user_t = dummy_user_t<const int&, s_value>;
    static int method()
    {
        printf("Hello %i!\n", i);
        return 0;
    }
};

// initialize s_value with method() to run it at program start
template<int i>
int my_struct_t<i>::s_value {my_struct_t<i>::method()};

// instantiate my_struct_t
template struct my_struct_t<6>;

int main()
{
    // nothing here
}

输出将是Hello 6!

此代码可在所有三个主要编译器上编译,但是当您将 s_value 设为 const 时,它将不再在 clang (3.4 - 7.0) 中工作,同时仍在 MSVC 和 GCC 中工作:

<source>:19:52: error: no member 'method' in 'my_struct_t<6>'; it has not yet been instantiated

const int my_struct_t<i>::s_value {my_struct_t<i>::method()};

                                               ^

<source>:10:51: note: in instantiation of static data member 'my_struct_t<6>::s_value' requested here

using value_user_t = dummy_user_t<const int&, s_value>;

                                              ^

<source>:21:17: note: in instantiation of template class 'my_struct_t<6>' requested here

template struct my_struct_t<6>;

            ^

<source>:11:16: note: not-yet-instantiated member is declared here

static int method()

           ^

1 error generated.

自己尝试一下:

使用非 const int:https ://godbolt.org/z/m90bgS

使用 const int:https ://godbolt.org/z/D3ywDq

你怎么看?铿锵有什么理由拒绝这个还是一个错误?

标签: c++clangcompiler-bug

解决方案


推荐阅读