类静态成员函数显式具体化的编译警告

发布时间 2023-05-06 21:05:58作者: green-cnblogs

本文描述了在定义类的静态成员函数模板的显式具体化时出现的一个编译警告问题,并在解释其原因后给出了对应的解决办法。

◆ 问题

环境:macOS Mojave (版本10.14.6), clang-1001.0.46.4 (-std=c++11)

头文件中定义了类的静态成员函数模板的显式具体化,代码编译没有出错,但出现如下警告信息:

warning: explicit specialization cannot have a storage class
static void print<bool>(bool v)
~~~~~~~     ^

◆ 示例

笔者定义了类的静态成员函数模板用于输出不同基础类型,

// .h file
class Std_Out
{

...

template <class _T>
static void print(_T v)
{
    cout.width(8);
    cout << v;
}

...

}

由于按照 ios_base::boolalpha 格式选项输出 bool 类型时,指定输出宽度(cout.width)无效,所以笔者为 bool 类型新定义了该模板的一个显式具体化,

// .h file
class Std_Out
{

...

template <>
static void print<bool>(bool v)
{
    cout.width(8);
    cout << (v ? "true" : "false");
}

...

}

编译该代码时会抛出前述编译警告。

◆ 原因

C++ 语法不允许类级别的静态成员函数模板的显式具体化。

◆ 解法

方法一,在头文件的类定义中去掉显式具体化的 static 关键字,

// .h file
template <>
//static
void print<bool>(bool v)
{
    cout.width(8);
    cout << (v ? "true" : "false");
}

方法二,在头文件中去掉显式具体化的声明,把代码移到类声明外或源文件中。

// in .h file
//template <>
//static void println<bool>(bool v)
//{
//    cout.width(8);
//    cout << (v ? "true" : "false") << endl;
//}


// in .cpp file 
template <>
void Std_Out::println<bool>(bool v)
{
    cout.width(8);
    cout << (v ? "true" : "false") << endl;
}

◆ 最后

完整示例 [gitee] cnblogs/17376662