gpt4 book ai didi

c++ - 为什么 C+ +'s ` 变量模板的行为不符合预期?

转载 作者:可可西里 更新时间:2023-11-01 16:37:57 25 4
gpt4 key购买 nike

#include <type_traits>

template<typename T>
struct remove_cvref
{
using type = std::remove_cv_t<
std::remove_reference_t<T>>;
};

template<typename T>
using remove_cvref_t =
typename remove_cvref<T>::type;

template<typename T>
constexpr bool isCc = std::is_copy_constructible_v<
remove_cvref_t<T>>;

class A final
{
public:
A() = default;
template<typename T, bool = isCc<T>> // error
A(T&&) {}
};

A f()
{
A a;
return a;
}

int main()
{}

错误信息:

error : constexpr variable 'isCc<const A &>' must be initialized by a constant expression
1>main.cpp(14): note: in instantiation of variable template specialization 'isCc<const A &>' requested here
1>main.cpp(15): note: in instantiation of default argument for 'A<const A &>' required here
1>C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\include\type_traits(847): note: while substituting deduced template arguments into function template 'A' [with T = const A &, b1 = (no value)]
1>main.cpp(8): note: in instantiation of variable template specialization 'std::is_copy_constructible_v<A>' requested here
1>main.cpp(14): note: in instantiation of variable template specialization 'isCc<A>' requested here
1>main.cpp(15): note: in instantiation of default argument for 'A<A>' required here
1>main.cpp(21): note: while substituting deduced template arguments into function template 'A' [with T = A, b1 = (no value)]

但是,如果我按如下方式更改类 A:

class A final
{
public:
A() = default;
template<typename T,
bool = std::is_copy_constructible_v<
remove_cvref_t<T>>> // ok
A(T&&) {}
};

那么一切就OK了。

为什么 C++ 的变量模板没有按预期运行?

最佳答案

std::is_copy_constructible_v<A> 的位置正在实例化,即紧接在 isCc 的定义之后, A不完整,而std::is_copy_constructible_v要求其模板参数完整。

此代码是否应该工作仍然是一个起草问题:Core Language Issue 287 ,因此一些编译器接受您的代码而其他编译器拒绝它是合理的。

在没有isCc的版本中,即使在点 std::is_copy_constructible_v<A>正在实例化,A是完整的1,因此所有编译器都乐意接受该代码。


1 标准中的相关规定:

[class.member]/6

A complete-class context of a class is a

  • function body,
  • default argument,
  • noexcept-specifier ([except.spec]),
  • contract condition, or
  • default member initializer

within the member-specification of the class ...

[class.member]/7

... The class is regarded as complete within its complete-class contexts ...

关于c++ - 为什么 C+ +'s ` 变量模板的行为不符合预期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53800974/

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