仅接受某些类型的 C++ 模板

2021-12-13 00:00:00 templates c++

在 Java 中,您可以定义泛型类,该类只接受扩展您选择的类的类型,例如:

public class ObservableList{...}

这是使用extends"关键字完成的.

C++ 中是否有一些简单的等价于 this 关键字?

解决方案

我建议使用 Boost 的 静态断言 功能与 is_base_of 来自 Boost Type Traits 库:

template类 ObservableList {BOOST_STATIC_ASSERT((is_base_of::value));//是的,需要双括号,否则逗号将被视为宏参数分隔符...};

在其他一些更简单的情况下,您可以简单地向前声明一个全局模板,但只为有效类型定义(显式或部分专门化)它:

template类 my_template;//声明,但不定义//int 是一个有效的类型模板<>class my_template{...};//所有指针类型都有效模板class my_template{...};//所有其他类型都无效,并且会导致链接器错误消息.

[次要编辑 6/12/2013:使用声明但未定义的模板将导致链接器,而不是编译器错误消息.]

In Java you can define generic class that accept only types that extends class of your choice, eg:

public class ObservableList<T extends List> {
  ...
}

This is done using "extends" keyword.

Is there some simple equivalent to this keyword in C++?

解决方案

I suggest using Boost's static assert feature in concert with is_base_of from the Boost Type Traits library:

template<typename T>
class ObservableList {
    BOOST_STATIC_ASSERT((is_base_of<List, T>::value)); //Yes, the double parentheses are needed, otherwise the comma will be seen as macro argument separator
    ...
};

In some other, simpler cases, you can simply forward-declare a global template, but only define (explicitly or partially specialise) it for the valid types:

template<typename T> class my_template;     // Declare, but don't define

// int is a valid type
template<> class my_template<int> {
    ...
};

// All pointer types are valid
template<typename T> class my_template<T*> {
    ...
};

// All other types are invalid, and will cause linker error messages.

[Minor EDIT 6/12/2013: Using a declared-but-not-defined template will result in linker, not compiler, error messages.]

相关文章