C++推断类成员的模板
C++ templates which infer class members
我知道我可以使用模板来假设模板使用的某些类具有某些成员变量; 但是,我想知道是否有办法显式声明模板类必须具有某个成员变量或函数?
我说的是这样的例子:
template <typename T>
class Assume
{
int value;
Assume(T* object) : value(T->AssumedMember) {};
};
class A
{
int AssumedMember;
A(int val) : AssumedMember(val) {};
};
int main()
{
A* a = new A(5);
Assume<A> assumer(a);
return 0;
}
我知道,至少使用 MSVC++ 中使用的编译器,类似于此示例的内容应该可以毫无问题地编译;
我只是想知道是否有一种方法可以声明,对于模板或类的使用,来自类型名 T 的 T 具有成员变量 AssumedMember。 到目前为止,真正理解 Assume 只有在与具有正确的所需成员(变量、函数或运算符)的类一起使用时才有效的唯一方法,要么必须编译并查看给定的编译器错误,要么自己通读整个模板以确定是否正在使用任何尚未定义的额外内容。
(另外,在一个不相关的说明中,有没有人知道将整个声明块声明为模板的方法? 好像使用类似的东西: template <typename T> { /*class... member definitions, etc..*/ }
声明整个定义块以使用相同的模板?
标准委员会一直在研究这个功能,称为"概念"。然而,它没有进入C++11。
但是,有两个编译器可以工作(具有各种功能)。 看看ConceptGCC或ConceptClang。
不,除了在模板的定义中声明模板要求之外,无法声明模板要求。例如,您可以使用static_asserts将这些要求放在定义中的前面,并提供更好的错误消息。
若要一次声明多个模板函数,可以使用带有静态成员函数的模板类:
template<typename T>
struct Foo {
static int bar(T t);
static T baz();
};
Foo<int>::bar(1);
auto s = Foo<std::string>::baz();
但是对于任何类型的模板声明,没有通用的方法可以做到这一点,我认为这不会为您节省很多东西。
用于static_asserts的自定义类型特征示例
我使用一些 C++11 的东西,但它也可以在 C++98 中完成
#include <type_traits>
// the custom type traits
template<typename T> struct exists : std::true_type {};
template<typename T>
struct has_value_type {
template<typename U>
static typename std::enable_if<exists<typename U::value_type>::value,char>::type
Test(int);
template<typename U> static int Test(...);
static constexpr bool value = sizeof(Test<T>(0)) == sizeof(char);
};
template<typename T>
struct has_member_i {
template<typename U>
static typename std::enable_if<0!=sizeof(&U::i),char>::type Test(int);
template<typename U> static int Test(...);
static constexpr bool value = sizeof(Test<T>(0)) == sizeof(char);
};
// your template for which you want to declare requirements
template<typename T>
void test(T t) {
static_assert(has_value_type<T>::value, "value_type must be a member type alias of T");
static_assert(has_member_i<T>::value, "i must be a member variable of T");
}
// one type that meets the requirements and one that doesn't
struct Foo {
typedef int value_type;
int i;
};
struct Bar {};
int main() {
test(Foo());
test(Bar());
}
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 助记符和指向成员语法的指针
- 用于访问容器<T>数据成员的正确 API
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 嵌套在类中时无法设置成员数据
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 将函数类成员映射到类本身内部
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 将公共但非静态的成员函数与ALGLIB集成
- 多成员Constexpr结构初始化
- 我们可以访问一个不存在的联盟的成员吗