0
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++ 为 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

对于 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': 等等等等

我无法弄清楚这里的问题是什么。有人可以帮我解决这个问题吗?

4

2 回答 2

1

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

于 2013-06-25T11:27:49.013 回答
1

那些:

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 中都有一个定义。

于 2013-06-25T11:38:46.987 回答