1

我有以下情况。foo我在自己的命名空间中有一个类my_lib

namespace my_lib{

template<typename T>
class foo{
    T data;
public:
    // blah blah
};

}

我正在尝试连接到另一个拥有自己的命名空间的库other_lib。我将此接口放在wrapper我自己的命名空间中my_libmy_lib::wrapper::copy具体来说,对于我需要访问的复制方法my_lib::foo::data,我需要实现以下内容:

namespace my_lib{
namespace wrapper{

template<typename T>
void copy(const foo<T>& my_foo, other_lib::foo<T>& other_foo)
{
    // copy my_foo.data to other_foo
}

}
}

要完成这个my_lib::wrapper::copy方法需要my_lib::foo类友。我可以通过一系列前向声明来实现这一点foo.h

// forward declare other_lib::foo
namespace other_lib{
template<typename T>
class foo;
}

namespace my_lib{

// forward declare wrapper::copy
namespace wrapper{
template<typename T>
void copy(const foo<T>& my_foo, other_lib::foo<T>& other_foo);
}

template<typename T>
class foo{
    T data;

    friend void copy(const foo<T>& my_foo, other_lib::foo<T>& other_foo);
public:
    // blah blah
};

}

这行得通,但我不喜欢它。一方面,它向文件中添加了很多other_libwrapper命名空间无关的东西。此外,在我的代码中使用其他库是可选的,但如果有人包含foo.h,他们将看到各种不相关的前向声明并开始想知道为什么......

我该如何解决这个设计?

4

1 回答 1

2

Syntactic tricks to get friend to work on other namespaces aside, the proper way is to fix your design. The interface of foo is simply not complete if it needs to grant a copy() function in some completely unrelated namespace friend access.

One way to go is to put copy() inside foo (and any other algorithm that users of foo need). When done right, this leads to a complete and usable class foo. E.g. take a look at std::list which has it's own sort() member function to take advantage of the list implementation details. However, this can quickly lead to a bloated class interface for foo (just look at std::string), so it's not recommended as a general rule.

Alternatively, you could provide a minimal set of data access member functions (preferably iterators, not handles to raw data) so that other classes can implement algorithms that work on foo. With a regular container (array, vector etc.) as data representation inside foo, this would be my recommendation for general use.

However, since your class foo has a tricky sparse matrix representation, you should probably try the algorithms-as-members-approach first.

于 2013-05-22T09:27:47.333 回答