#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()
{}
The error message:
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)]
However, if I change the class A
as follows:
class A final
{
public:
A() = default;
template<typename T,
bool = std::is_copy_constructible_v<
remove_cvref_t<T>>> // ok
A(T&&) {}
};
Then everything is ok.
Why does C++'s variable template
not behave as expected?
ISO C++ Latest Draft Standard (/std:c++latest)
and it compiles and builds fine, also I even called the functionf();
inside of main and it still built compiled and ran and exited without errors. – DogvaneA(T&&)
is a copy constructor, it will take part in the determination of whetherT obj(std::declval<Args>()...);
is well formed instd::is_copy_constructible
. In other words,std::is_copy_constructible
depends on itself. So some strange behavior is actually expected. As for why the second approach will seems to "work", that might be some SIFAE stuff breaks the circular dependency, and drop this template. – Heartbroken::value
member disappears instd::is_copy_constructible
– Heartbroken