为什么在 C++ 中使用静态模板类成员作为友元模板函数默认参数会出现编译错误?如何解决?
代码如下:
#include <iostream>
template<typename T>
void func(T n);
template<typename T>
class MyClass
{
private:
static T statTemp;
public:
friend void func<>(T n);
};
template<typename T>
T MyClass<T>::statTemp(1);
template<typename T>
void func(T n = MyClass<T>::statTemp)
{
std::cout << n << std::endl;
}
int main()
{
func<int>();
}
编译时:
g++ -std=c++11 main.cpp
error: redeclaration of 'template<class T> void func(T)' may not have default arguments [-fpermissive]
void func(T n = MyClass<T>::statTemp)
^~~~
In function 'int main()':
error: no matching function for call to 'func<int>()'
func<int>();
^
note: candidate: 'template<class T> void func(T)'
void func(T n = MyClass<T>::statTemp)
^~~~
note: template argument deduction/substitution failed:
note: candidate expects 1 argument, 0 provided
func<int>();
^
Visual Studio 2017
C2672 "func": No matching overloaded function found.
最佳答案
该语言不允许将模板函数的默认参数添加到同一范围内函数的后续声明中。
C++17 标准草案 n4659 指出:
11.3.6 Default arguments [dcl.fct.default]
...
4 For non-template functions, default arguments can be added in later declarations of a function in the same scope.
由于 func
是一个模板函数,因此不允许在同一范围内的 func
的后续声明中添加默认参数。
因此 GCC 正确地拒绝了这个:
error: redeclaration of 'template<class T> void func(T)' may not have default arguments [-fpermissive]
void func(T n = MyClass<T>::statTemp)
关于C++静态模板类成员作为友元模板函数默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54859285/