C++推断类成员的模板

C++ templates which infer class members

本文关键字:成员 C++      更新时间:2023-10-16

我知道我可以使用模板来假设模板使用的某些类具有某些成员变量; 但是,我想知道是否有办法显式声明模板类必须具有某个成员变量或函数?

我说的是这样的例子:

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());
}