为了在程序启动时强制执行模板方法,可以使用静态方法初始化静态成员。然后,该方法在程序启动时针对模板类的每个实例进行运行:
#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.
亲自尝试:
使用非常量整数:https://godbolt.org/z/m90bgS
使用const int:https://godbolt.org/z/D3ywDq
您怎么看?是什么原因导致clang拒绝了此消息,还是有bug?