为什么自动类型推导不适用于 constexpr 成员引用?
Why does automatic type deduction not work for constexpr member referencing?
在示例代码中,用 C++17 编译:
template <typename T = int>
struct A
{
static constexpr double b = 0.5;
};
int main()
{
A a; // compiles
double c = A<>::b; // compiles
double d = A::b; // fails to compile
// ...
return 0;
}
A::b
编译失败,因为:
main.cpp:13:16: error: 'template<class T> struct A' used without template arguments
13 | double d = A::b; // fails to compile
我认为在 C++17 中自动模板类型推导会解决这个问题,因为我有默认的模板参数。我错过了什么?
每个实例化的 class 实例都有自己的 A<T>::b
成员。
#include <iostream>
template <typename T = int>
struct A
{
static constexpr double b = 0.5;
};
int main()
{
std::cout << &A<int>::b << "\n";
std::cout << &A<char>::b << "\n";
return 0;
}
使用带有选项 -std=c++17
的 clang++13 编译。输出:
0x402008
0x402018
想想如果A::b
可以编译,编译器会选择哪个地址
实例https://godbolt.org/z/GqhjMvoz6
至于默认模板参数编译失败double d = A::b;
,这是规则,模板必须实例化使用尖括号<, >
.
在示例代码中,用 C++17 编译:
template <typename T = int>
struct A
{
static constexpr double b = 0.5;
};
int main()
{
A a; // compiles
double c = A<>::b; // compiles
double d = A::b; // fails to compile
// ...
return 0;
}
A::b
编译失败,因为:
main.cpp:13:16: error: 'template<class T> struct A' used without template arguments
13 | double d = A::b; // fails to compile
我认为在 C++17 中自动模板类型推导会解决这个问题,因为我有默认的模板参数。我错过了什么?
每个实例化的 class 实例都有自己的 A<T>::b
成员。
#include <iostream>
template <typename T = int>
struct A
{
static constexpr double b = 0.5;
};
int main()
{
std::cout << &A<int>::b << "\n";
std::cout << &A<char>::b << "\n";
return 0;
}
使用带有选项 -std=c++17
的 clang++13 编译。输出:
0x402008
0x402018
想想如果A::b
可以编译,编译器会选择哪个地址
实例https://godbolt.org/z/GqhjMvoz6
至于默认模板参数编译失败double d = A::b;
,这是规则,模板必须实例化使用尖括号<, >
.