在G++中如何做到这一点?
这段代码对于VC++是可以的。
#include<iostream>
#include<utility>
#include<typeinfo>
template<typename T>
struct ss
{
template<typename F>
static constexpr auto f()
{
printf("template !\n");
}
template<>
static constexpr auto f<int>()
{
printf("int !\n");
}
};
int main(int argc, const char* argv[])
{
return ss<int>::f<char>();
}
在线:https://godbolt.org/z/qgq6bp
source>:14:14: error: explicit specialization in non-namespace scope 'struct ss<T>'
14 | template<>
| ^
<source>:15:34: error: template-id 'f<int>' in declaration of primary template
15 | static constexpr auto f<int>()
| ^
<source>: In function 'int main(int, const char**)':
<source>:24:27: error: void value not ignored as it ought to be
24 | return ss<int>::f<char>();
| ~~~~~~~~~~~~~~~~^~
ASM generation compiler returned: 1
<source>:14:14: error: explicit specialization in non-namespace scope 'struct ss<T>'
14 | template<>
| ^
<source>:15:34: error: template-id 'f<int>' in declaration of primary template
15 | static constexpr auto f<int>()
| ^
<source>: In function 'int main(int, const char**)':
<source>:24:27: error: void value not ignored as it ought to be
24 | return ss<int>::f<char>();
| ~~~~~~~~~~~~~~~~^~
Execution build compiler
这是海合会的问题。根据CWG727,在任何作用域中都应该允许显式专门化,包括在类作用域中。
可以在定义相应主模板的任何作用域中声明显式专门化(N4868.9.8.2.3[namespace.memdef],11.4[class.mem],13.7.3[temp.mem])。
要使它与GCC一起工作,必须将显式专门化放在名称空间作用域中,这意味着必须同时显式专门化包含类。也可以使用helper函数模板,例如。
template <typename F>
constexpr auto foo()
{
printf("template !\n");
}
template <>
constexpr auto foo<int>()
{
printf("int !\n");
}
template<typename T>
struct ss
{
template<typename F>
static constexpr auto f()
{
return foo<F>();
}
};