泛型 class 之外的函数定义产生编译错误
Definition of a function outside of a generic class is producing a compilation error
上下文
我编写了以下最小工作示例
#include <iostream>
template <typename T>
struct A {
enum myenum {faa, fee, fii};
myenum m_m;
A(const myenum& m = faa): m_m(m) {}
};
int main() {
A<int> a1;
A<int> a2(A<int>::fii);
std::cout << a1.m_m << std::endl
<< a2.m_m << std::endl;
return 0;
}
编译并执行它的结果是
$ g++ main.cpp && ./a.out
0
2
问题
但是,当函数的定义写在class之外(即如下图)
#include <iostream>
template <typename T>
struct A {
enum myenum {faa, fee, fii};
myenum m_m;
A(const myenum& m);
};
template <typename T>
A<T>::A(const myenum& m = A<T>::faa): m_m(m) {}
int main() {
A<int> a2(A<int>::fii);
std::cout << a2.m_m << std::endl;
return 0;
}
我得到以下编译错误
$ g++ main.cpp && ./a.out
main.cpp:11:1: error: redeclaration of ‘A<T>::A(const A<T>::myenum&)’ may not have default arguments [-fpermissive]
11 | A<T>::A(const myenum& m = A<T>::faa): m_m(m) {}
| ^~~~
问题
我怎样才能摆脱这个编译错误?
您必须在声明中指定 default argument,并将其从定义中删除。
For member functions of class templates, all defaults must be provided in the initial declaration of the member function.
template <typename T>
struct A {
enum myenum {faa, fee, fii};
myenum m_m;
A(const myenum& m = faa);
};
template <typename T>
A<T>::A(const myenum& m): m_m(m) {}
上下文
我编写了以下最小工作示例
#include <iostream>
template <typename T>
struct A {
enum myenum {faa, fee, fii};
myenum m_m;
A(const myenum& m = faa): m_m(m) {}
};
int main() {
A<int> a1;
A<int> a2(A<int>::fii);
std::cout << a1.m_m << std::endl
<< a2.m_m << std::endl;
return 0;
}
编译并执行它的结果是
$ g++ main.cpp && ./a.out
0
2
问题
但是,当函数的定义写在class之外(即如下图)
#include <iostream>
template <typename T>
struct A {
enum myenum {faa, fee, fii};
myenum m_m;
A(const myenum& m);
};
template <typename T>
A<T>::A(const myenum& m = A<T>::faa): m_m(m) {}
int main() {
A<int> a2(A<int>::fii);
std::cout << a2.m_m << std::endl;
return 0;
}
我得到以下编译错误
$ g++ main.cpp && ./a.out
main.cpp:11:1: error: redeclaration of ‘A<T>::A(const A<T>::myenum&)’ may not have default arguments [-fpermissive]
11 | A<T>::A(const myenum& m = A<T>::faa): m_m(m) {}
| ^~~~
问题
我怎样才能摆脱这个编译错误?
您必须在声明中指定 default argument,并将其从定义中删除。
For member functions of class templates, all defaults must be provided in the initial declaration of the member function.
template <typename T>
struct A {
enum myenum {faa, fee, fii};
myenum m_m;
A(const myenum& m = faa);
};
template <typename T>
A<T>::A(const myenum& m): m_m(m) {}