[英]C++ 17 How to specialize static function template in class template
如何在 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
這是 GCC 的問題。 根據CWG 727 ,應允許在任何 scope 中進行顯式特化,包括在 class scope 中。
可以在可以定義相應主模板的任何 scope 中聲明顯式特化( N4868 .9.8.2.3 [namespace.memdef]、11.4 [class.mem]、13.7.3 [temp.mem])。
要使其與 GCC 一起使用,您必須將顯式特化放在命名空間 scope 中,這意味着您必須同時顯式特化包含的 class 模板ss
。 或者您可以使用 function 模板助手,例如
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>();
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.