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

2023-02-23C/C++开发问题
2

本文介绍了仅接受某些类型的 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.]

这篇关于仅接受某些类型的 C++ 模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6