3

Is it possible to declare a template function where a certain type is derived from let's say B?

My goal is to achieve something like this:

template<class T : std::ostream> void write(T os) {
    os << "...";
} 

template<class T : std::string> void write(T s) {
   // ...
}

Edit: I know it is not a solid example since it is not usual to derive from a string, but note that it's just a example.

So any solution like a workaround is welcome, however I would like to be able to explicit instantiate the template functions.

4

2 回答 2

9

是的,使用 C++11<type_traits>可以实现。
如果你只有 C++03,你可以用 Boost<type_traits>代替。

template <typename T>
typename std::enable_if<std::is_base_of<std::ostream, T>::value>::type
write(T& os) {
}
于 2013-06-19T16:04:09.397 回答
0

任何派生自 std::ostream 的对象都可以用作参数

void write(std::ostream os) {
    os << "...";
} 
于 2013-06-19T16:14:50.007 回答