c++ - FreeBSD 上 c++ 模板的奇怪编译器错误

标签 c++ templates freebsd

I have the following:

class obj
{

    template<typename T>
    inline int foo(T val) const;
};


template<typename T>
int obj::foo(T val)  const
{
    //Do something for PODs
}

template<>
int obj::foo<std::vector<bool>::reference>(std::vector<bool>::reference val) const
{
    //Do something for a boolean in vector of booleans.
}

template<>
int obj::foo<std::string>(std::string var) const
{
    //Do something for string. 
}

在为 FreeBSD 使用 g++ 编译时,编译器会报错:

In function int obj::foo<std::_Bit_reference>(std::_Bit_reference) const': /path/to/file.h:22: multiple definition of int obj::foo<std::_Bit_reference>(std::_Bit_reference) const' /path/to/file.h:22 first defined here

对于 std::string 也是如此:

In function int obj::foo<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >(std::basic_string<char, std::char_traits<char>, std::allocator<char> >) const': 等等等等

我不知道这里的问题是什么。有人可以帮我解决这个问题吗?

最佳答案

那些:

template<>
int obj::foo<std::vector<bool>::reference>(std::vector<bool>::reference val) const
{
    //Do something for a boolean in vector of booleans.
}

template<>
int obj::foo<std::string>(std::string var) const
{
    //Do something for string. 
}

是专门化,因此函数定义应该在 .cpp 中(但在 header 中保留声明)而不是在 header 中。将它们放在 header 中会导致每个包含 header 的 .cpp 中都有一个定义。

关于c++ - FreeBSD 上 c++ 模板的奇怪编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17296022/

相关文章:

c++ - 如何为缓冲区声明适当的大小

c++ - 如何在 C++ 中使用模板和 OOP?

c - FreeBSD的namei()调用的LOOKUP操作及其错误

node.js - 我们可以使用NGINX作为模板引擎的Web应用程序吗

c - system() 的退出代码不符合预期

python - 在 python 中如何获取 kern.module_path 的值?

c++ - chromium 源码中的 BASE_EXPORT 有什么作用?

c++ - 将 Child 对象数组传递给接受 Parent* 的函数

c++ - 使用 sizeof 计算数组中元素数时的不同结果

c++ - 在 C++ 中创建从 io 类继承的异常类