gpt4 book ai didi

c++ - 如何使用此类的实例在类中引用 typedef?

转载 作者:太空宇宙 更新时间:2023-11-03 10:33:18 25 4
gpt4 key购买 nike

有没有办法让这段代码正常工作,就像用点符号调用 static 函数时一样?

struct A{
static void f(){ }
typedef int t;
};

template<typename T> void f(){}

int main(){
A a;
a.f(); //legit
f<a.t>(); //‘a’ cannot appear in a constant-expression, ‘.’ cannot appear in a constant-expression
a.t somevar; //invalid use of ‘A::t’
f<a::t>(); //‘a’ cannot appear in a constant-expression
a::t somevar; //‘a’ is not a class, namespace, or enumeration
}

编辑:伙计们,请在发布前阅读问题并测试您的代码。这里的重点不是使用 A::t,而是通过 A实例“调用”t,就像您可以使用静态方法一样。

最佳答案

你必须使用 A::t 而不是 a.t 因为 typedef 就像 staticaA 的实例。


编辑:与我上面所说的相反,它并不总是“像static”。对于静态成员,有这个特殊规则:

A static member s of class X may be referred to using the qualified-id expression X::s; it is not necessary to use the class member access syntax (5.2.5) to refer to a static member. A static member may be referred to using the class member access syntax, in which case the object expression is evaluated. [ Example:

struct process {
static void reschedule();
};
process& g();

void f() {
process::reschedule(); // OK: no object necessary
g().reschedule(); // g() is called
}

因为 typedef 不是静态成员,不是,所以这个语法是无效的。

给定实例 a 而不是这个语法糖,获取 t 的唯一方法是获取它的类型。 C++11 为我们提供了一个工具:

typedef decltype(a) a_type;
f<a_type::t>();
a_type::t somevar;

但是,我看不到它的实际用途(好吧,也许在宏中,但每个人都知道模板更好)。

关于c++ - 如何使用此类的实例在类中引用 typedef?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10157296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com