【发布时间】:2019-12-27 18:58:48
【问题描述】:
template <typename T>
struct A
{
static constexpr T obj {};
static constexpr bool noexcept_copy = noexcept( T{obj} );
static void UsesCopy() { T{obj}; }
static constexpr int C = 1;
};
struct NoCopy
{
constexpr NoCopy() = default;
NoCopy(const NoCopy&) = delete;
};
int main()
{
return A<NoCopy>::C;
}
上面的代码被GCC编译成功,但是Clang给出编译错误:
tmp.cpp:6:57: error: call to deleted constructor of 'NoCopy'
static constexpr bool noexcept_copy = noexcept( T{obj} );
^~~~~~
tmp.cpp:20:16: note: in instantiation of template class 'A<NoCopy>' requested here
return A<NoCopy>::C;
^
tmp.cpp:15:9: note: 'NoCopy' has been explicitly marked deleted here
NoCopy(const NoCopy&) = delete;
^
1 error generated.
A::UsesCopy 函数也使用复制构造函数,但编译器不会抱怨那里使用了已删除函数。 UsesCopy 函数和 noexcept_copy constexpr 有什么区别?两者都使用NoCopy类的复制构造函数,两者都没有使用,但是constexpr定义会产生编译错误,函数定义不会。
PS. Clang 使用-std=c++17 或-std=c++2a 编译上面的代码,但不使用-std=c++11 或-std=c++14。
【问题讨论】:
-
clang 在这里是正确的 - 即使没有使用最后你确实使用对实例化类型的 c-tor 的调用 - 你删除的那个 - 解决方案:使用SFINAE
-
temp.spec#temp.inst-10 "实现不应隐式实例化函数模板、变量模板、成员模板、非虚拟成员函数、成员类、静态数据成员类模板或 constexpr if 语句 ([stmt.if]) 的子语句,除非需要这样的实例化。"
-
对我来说它只能在 C++17 中工作,而不是 C++14。我怀疑 constexpr 变量现在是内联的事实
-
静态数据成员和非删除成员函数的定义不应该被实例化([temp.inst]/(2.1))。但是在这个特定的 sn-p 中,静态 constexpr 数据成员的类内初始化不是 C++17 之前的定义。我会说在这种情况下行为未指定。 (虽然它不影响 C++17 及更高版本中的
static constexpr bool成员,但对于不是constexpr的static const bool成员仍然很重要。) -
这似乎与 a number of core issues 相关,主题是实例化类模板及其
constexpr成员时发生的情况。
标签: c++ templates gcc clang language-lawyer