【发布时间】:2015-08-24 14:53:26
【问题描述】:
我有一个模板类A 和一个模板函数f,它返回A 对象。我希望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 就这里的内容达成一致。如果我不将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>();
我怎样才能让每个人都开心?
【问题讨论】:
-
查看this Q&A 了解类似的错误
标签: c++ c++11 gcc clang constexpr