【发布时间】:2020-11-18 16:45:38
【问题描述】:
举个例子:
#include <iostream>
#include <type_traits>
#include <utility>
struct Bar
{
Bar() = default;
Bar(Bar const&) noexcept(false) = default;
Bar(Bar&&) noexcept(true) = default;
};
struct Baz
{
Baz() = default;
Baz(Baz const&) noexcept(true) = default;
Baz(Baz&&) noexcept(false) = default;
};
template<typename T>
class Foo
{
template<typename U, typename V>
using enable_if_same = std::enable_if<std::is_same<typename std::remove_reference<U>::type, V>::value, U>;
public:
template<typename U>
Foo(typename enable_if_same<U, T>::type&& val) // noexcept( ? )
: _val(std::forward<U>(val))
{
}
protected:
T _val;
};
int main(void)
{
std::cout << "Is the Bar copy constructor noexcept? " << std::is_nothrow_copy_constructible<Bar>::value << "\n";
std::cout << "Is the Bar move constructor noexcept? " << std::is_nothrow_move_constructible<Bar>::value << "\n";
std::cout << "Is the Foo<Bar> copy constructor noexcept? " << std::is_nothrow_copy_constructible<Foo<Bar>>::value << "\n";
std::cout << "Is the Foo<Bar> move constructor noexcept? " << std::is_nothrow_move_constructible<Foo<Bar>>::value << "\n";
std::cout << "\n";
std::cout << "Is the Baz copy constructor noexcept? " << std::is_nothrow_copy_constructible<Baz>::value << "\n";
std::cout << "Is the Baz move constructor noexcept? " << std::is_nothrow_move_constructible<Baz>::value << "\n";
std::cout << "Is the Foo<Baz> copy constructor noexcept? " << std::is_nothrow_copy_constructible<Foo<Baz>>::value << "\n";
std::cout << "Is the Foo<Baz> move constructor noexcept? " << std::is_nothrow_move_constructible<Foo<Baz>>::value << "\n";
return 0;
}
编译并运行上述代码会产生预期的输出:
Is the Bar copy constructor noexcept? 0
Is the Bar move constructor noexcept? 1
Is the Foo<Bar> copy constructor noexcept? 0
Is the Foo<Bar> move constructor noexcept? 1
Is the Baz copy constructor noexcept? 1
Is the Baz move constructor noexcept? 0
Is the Foo<Baz> copy constructor noexcept? 1
Is the Foo<Baz> move constructor noexcept? 0
我很想知道,但是,是否可以明确指定 Foo(U&&) 构造函数的 noexcept-ness,采用转发引用(即我需要在注释掉的部分中用什么替换 ?上面的 noexcept 说明符)?
【问题讨论】:
标签: c++ perfect-forwarding noexcept forwarding-reference