gpt4 book ai didi

c++ - 类成员上的 Decltype 作为模板参数

转载 作者:行者123 更新时间:2023-11-28 02:43:14 25 4
gpt4 key购买 nike

我正在尝试将类成员的类型作为模板参数传递。为此,我使用以下代码:

class C
{
public:
int a;
};
class B
{
public:
template<typename _T> void Test() {}
// Specialize for int for Test testing purposes.
template<> void Test<int>() { printf("Success!\n"); }
};

//Later:
B b;
C c;
b.Test<decltype(c.a)>();

这给了我以下错误:

error C2662: 'void B::Test(void)' : cannot convert 'this' pointer from 'C' to 'B &' Reason: cannot convert from 'C' to 'B' Conversion requires a second user-defined-conversion operator or constructor

但是,如果我使用以下代码,它确实有效:

decltype(c.a) d;
b.Test<decltype(d)>();

如果我只是直接使用类成员,为什么它不起作用?我正在使用 Visual Studio 2012。

最佳答案

7.1.6.2(4)

For an expression e, the type denoted by decltype(e) is defined as follows:

  • if e is an unparenthesized id-expression or an unparenthesized class member access (5.2.5), decltype(e) is the type of the entity named by e.
  • If there is no such entity, or if e names a set of overloaded functions, the program is ill-formed;
  • otherwise, if e is an xvalue, decltype(e) is T&&, where T is the type of e;
  • otherwise, if e is an lvalue, decltype(e) is T&, where T is the type of e;
  • otherwise, decltype(e) is the type of e.

VS2012 似乎忘记了(或从未被告知)我加粗的部分,即 e 是未加括号的类成员访问的情况。因此,当 e 是左值时,它可能会回到规则,因此对于 VS2012 decltype(c.a) 表示 int& (对int).

您的示例还包含一个以 _ 开头的标识符和一个大写字母 (_T),这是未定义的行为。参见 What are the rules about using an underscore in a C++ identifier?

关于c++ - 类成员上的 Decltype 作为模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25248680/

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