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

A weird compiler error for c++ templates on FreeBSD

本文关键字:一个 错误 编译器 c++ 上的 FreeBSD      更新时间:2023-10-16
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. 
}

当使用 g++ for FreeBSD 编译时, 编译器抱怨:

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

标准::字符串也是如此:

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中(但在标头中保留声明(而不是在标头中。 将它们放在标头中会导致每个.cpp中都有一个定义,其中包括标头。

int obj::foo(T val) const;末尾的分号

相关文章: