【发布时间】:2019-03-17 14:35:04
【问题描述】:
我在让它工作时遇到了一些麻烦。这是我通过编译阶段的问题的 MVCE
template<typename T>
struct foo
{
using type = T;
friend type bar(foo const& x) { return x.X; }
foo(type x) : X(x) {}
private:
type X;
};
template<typename> struct fun;
template<typename T> fun<T> bar(foo<T> const&, T); // forward declaration
template<typename T>
struct fun
{
using type = T;
friend fun bar(foo<type> const& x, type y)
{ return {bar(x)+y}; }
private:
fun(type x) : X(x) {}
type X;
};
int main()
{
foo<int> x{42};
fun<int> y = bar(x,7); // called here
};
编译器需要前向声明来解析main() 中的调用(原因参见this answer)。但是,编译器现在在链接/加载阶段抱怨:
架构 x86_64 的未定义符号:“有趣 bar(foo const&, int)",引用自: foo-00bf19.old 中的 _main:未找到架构 x86_64 的符号
即使函数是在友元声明中定义的。相反,我将定义移到struct func<> 之外,即
template<typename T>
struct fun
{
using type = T;
friend fun bar(foo<type> const& x, type y);
private:
fun(type x) : X(x) {}
type X;
};
template<typename T>
inline fun<T> bar(foo<T> const& x, T y)
{ return {bar(x)+y}; }
编译失败
foo.cc:29:10: error: calling a private constructor of class 'fun<int>'
{ return {bar(x)+y}; }
那么,我怎样才能让它工作呢? (编译器:Apple LLVM 9.0.0 版(clang-900.0.39.2),c++11)
【问题讨论】: