有相当于<?延伸T>,<?超级T>在C++中?

use*_*855 17 c++ java generics templates

  1. 是否有相当于<? extends T>,<? super T>在C++?

  2. 此外,没有<? extends T>,<? super T>工作,即使T是在Java中的接口?

ppr*_*mek 13

它没有像Java那样很好的语法糖,但它可以通过boost/type_traits很好地管理.有关详细信息,请参阅http://www.boost.org/doc/libs/1_40_0/libs/type_traits/doc/html/index.html.

#include <boost/type_traits.hpp>
#include <boost/static_assert.hpp>

class Base {};
class Derived_from_Base : public Base {};
class Not_derived_from_Base {};

template<typename BASE, typename DERIVED>
void workOnBase()
{
    BOOST_STATIC_ASSERT((boost::is_base_of<BASE, DERIVED>::value)); 
}

int main()
{
    workOnBase<Base, Derived_from_Base>();     // OK
    workOnBase<Base, Not_derived_from_Base>(); // FAIL
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

1> d:...\main.cpp(11):错误C2027:使用未定义类型'boost :: STATIC_ASSERTION_FAILURE'1> 1> [1> x = false 1>]


Jes*_*erE 6

回答你的第二个问题:是的.就泛型而言,接口被视为与真实类相同.

我将把第一个问题留给更多精通C++的人.