C++静态模板类成员作为友元模板函数默认参数

标签 c++ templates default-parameters default-arguments function-templates

为什么在 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/

相关文章:

php - 根据先前的参数获取默认参数的值

c++ - ostringstream 打破了 cout?

C++ 类 this-> 错误

c++ - 从 xvfb 读取像素数据

c++ - 使用模板将一般参数传递给函数

c++ - Qt nmake : error C3203: 'map' : unspecialized class template can't be used as a template argument for template parameter 'base' , 需要一个真实类型

带有可选参数的 JavaScript 函数

c# - Visual C# 在调用包装的 C++\CLI dll 中的 Lapack 时抛出 System.AccessViolationException

带有纯虚函数的C++模板返回值

c# - 如何为表达式树传递默认参数?