c++ - 为什么这段代码可以在 Coliru 上编译,但不能在 Xcode 上编译?

标签 c++ xcode templates abstract-class crtp

我有时将前者用作测试平台,然后将代码移动到我在 XCode 中的真实项目中。在这种情况下,这对我不起作用。以下代码在 Coliru 上编译和运行(参见 cat/Archive2/48/70c3935989bffb/main.cpp),但在 XCode 上不编译和运行。

#include <cassert>

template <typename T, typename P>
class Permutation
{
public:

    virtual bool operator==(const P& other) const;
    // other member functions not listed here use the type T
};

template <typename T>
class SmallPermutation : public Permutation<T, SmallPermutation<T> >
{    
public:

    SmallPermutation(int i);    
    virtual bool operator==(const SmallPermutation& other) const;
    int code;
    // other member functions not listed here use the type T
};


template <typename T>
SmallPermutation<T>::SmallPermutation(int i)
{
    code = i;
}

template <typename T>
bool SmallPermutation<T>::operator==(const SmallPermutation& other)  const
{
    return code == other.code;
}

int main()
{    
    SmallPermutation<int> a(4);
    SmallPermutation<int> b(7);
    SmallPermutation<int> c(4);

    assert(a == c);
    assert(!(a == b));

    return 0;
}

这是来自 XCode 的错误消息的一部分(我不明白):

Undefined symbols for architecture x86_64:
"Permutation<int, SmallPermutation<int> >::operator==(SmallPermutation<int> const&) const", referenced from:
  vtable for Permutation<int, SmallPermutation<int> > in permutationTest.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

代码有什么不规范的地方吗? XCode 中是否有我需要调整的构建/编译/环境设置?

背景:我有几个具有相同接口(interface)的(模板)类,我希望它们都继承自一个抽象类。模板的东西使这个任务有点困难。我使用(可能是错误的)一种称为 CRTP(奇怪的重复模板模式)的技术来实现它。

最佳答案

如果你声明了一个非纯虚函数,比如Permutation类中的operator==函数,那么它需要有一个定义,你必须提供一个函数的函数体。

解决方案是使其变得纯净:

virtual bool operator==(const P& other) const = 0;

或者提供一个虚拟实现:

virtual bool operator==(const P& other) const { return false; }

关于c++ - 为什么这段代码可以在 Coliru 上编译,但不能在 Xcode 上编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36866022/

相关文章:

c++ - 在 bool 矩阵中查找唯一行(帮助解决 std::string 的垃圾输出)

objective-c - iCloud Drive 文件夹

c++ - 两个模板类互相用作模板参数

c++ - 使用 auto 作为参数是否有负面影响?

c++ - 是否可以使用 `std::copy` 将值从可变大小的数组复制到容器?

c++ - 从函数返回 am Eigen::Tensor slice

c++ - 为什么必须在哪里放置 “template”和 “typename”关键字?

在构造中定义的 C++ 容器

ios - Xcode 7 大小类问题?

ios - Swift 中基于图像的动画