提问者:小点点

C++17如何在类模板中实现静态函数模板的专门化


在G++中如何做到这一点?

  • 声明类模板ss。[确定]
  • 取消静态函数模板f[ok]
  • 如何专门化f?[错误]

这段代码对于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 

共1个答案

匿名用户

这是海合会的问题。根据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>();
    }

};

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++17|何在|类|模板|中|静态|函数|模板|专门化)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?