在Java中,您可以定义通用类,它只接受扩展您选择的类的类型,例如:
public class ObservableList<T extends List> {
...
}
Run Code Online (Sandbox Code Playgroud)
这是使用"extends"关键字完成的.
在C++中是否有一些简单的等效关键字?
在C#中,我们可以定义一个泛型类型,它对可用作泛型参数的类型施加约束.以下示例说明了泛型约束的用法:
interface IFoo
{
}
class Foo<T> where T : IFoo
{
}
class Bar : IFoo
{
}
class Simpson
{
}
class Program
{
static void Main(string[] args)
{
Foo<Bar> a = new Foo<Bar>();
Foo<Simpson> b = new Foo<Simpson>(); // error CS0309
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法可以在C++中对模板参数施加约束.
C++ 0x本身支持这个,但我说的是当前的标准C++.
是否有相当于<? extends T>,<? super T>在C++?
此外,没有<? extends T>,<? super T>工作,即使T是在Java中的接口?
鉴于以下内容:
StreamLogger& operator<<(const char* s) {
elements.push_back(String(s));
return *this;
}
StreamLogger& operator<<(int val) {
elements.push_back(String(asString<int>(val)));
return *this;
}
StreamLogger& operator<<(unsigned val) {
elements.push_back(String(asString<unsigned>(val)));
return *this;
}
StreamLogger& operator<<(size_t val) {
elements.push_back(String(asString<size_t>(val)));
return *this;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法消除重复?我想使用模板,但我只想要它用于以下类型:const char*int,unsigned和size_t
我有一个类模板,打算使用其参数K作为地图的关键.
有没有办法将模板参数限制为符合std :: map中的Key的类型?
我意识到,即使没有这样的约束,编译器也会吐出一堆模板错误,比如K没有operator < (),但如果我能在指定需求时使代码更明显,那就更好了.
欢迎使用C++ 11解决方案.
template< typename K >
class Foo
{
// lots of other code here...
private:
std::map< K, size_t > m_map;
};
Run Code Online (Sandbox Code Playgroud) 是否可以限制可以实例化模板的类型(即,如果我使用,则会出现编译器错误template<type_not_allowed>)?