我有一个模板类A
和一个返回A
对象的模板函数f
。 我想让f<T>
成为A<T>
的朋友,并仍然保持constexpr
我有一个模板类A
和一个返回A
对象的模板函数f
。我希望f<T>
成为A<T>
类的友元,并且仍然具有constexpr
属性。
template <typename T>
class A;
template <typename T>
constexpr A<T> f();
//f<T> is a friend of A<T>
template <typename T>
class A {
friend /* constexpr? */ A f<T>();
constexpr A() {}
};
template <typename T>
constexpr A<T> f() { return {}; }
int main() {
constexpr auto a = f<void>();
}
我无法让clang和gcc在这里达成共识。如果在friend声明中不加入constexpr
,gcc可以正常工作,但是clang无法编译它,会出现以下错误:
clang和gcc无法就此达成共识。如果在友元声明中不使用constexpr
,那么gcc可以正常工作,但是clang会出现编译错误:
main.cpp:18:18: error: constexpr variable 'a' must be initialized by a constant expression
constexpr auto a = f<void>();
^ ~~~~~~~~~
main.cpp:18:23: note: non-constexpr function 'f<void>' cannot be used in a constant expression
constexpr auto a = f<void>();
^
main.cpp:9:12: note: declared here
friend A f<T>();
如果我在友元声明中标记为constexpr
,clang编译可行但gcc会给出错误:
main.cpp:9:27: error: 'constexpr' is not allowed in declaration of friend template specialization 'A<T> f<T>()'
friend constexpr A f<T>();
我怎样才能让每个人都开心呢?