显式默认模板化构造函数
Explicitly defaulting a templated constructor
我尝试使用以下技术根据 class 模板参数的 属性 有条件地创建 默认构造函数 = default;
:
#include <type_traits>
#include <utility>
#include <iostream>
#include <cstdlib>
template< typename T >
struct identity
{
};
template< typename T >
struct has_property
: std::false_type
{
};
template< typename T >
struct S
{
template< typename X = T,
typename = std::enable_if_t< !has_property< X >::value > >
S(identity< X > = {})
{ std::cout << __PRETTY_FUNCTION__ << std::endl; }
template< typename X = T,
typename = std::enable_if_t< has_property< X >::value > >
#if 0
S() = default;
#else
S()
{ std::cout << __PRETTY_FUNCTION__ << std::endl; }
#endif
};
struct A {};
struct B {};
template<>
struct has_property< B >
: std::true_type
{
};
int main()
{
S< A >{};
S< B >{};
return EXIT_SUCCESS;
}
但是对于#if 1
它给出了一个错误:
main.cpp:32:11: error: only special member functions may be defaulted
S() = default;
^
template< ... > S()
不是 S
的 默认构造函数 的声明吗?
我将来可以使用即将到来的概念实现这样的调度吗?
我认为[dcl.fct.def.default]涵盖了这一点:
A function that is explicitly defaulted shall:
- be a special member function,
- have the same declared function type (except for possibly differing ref-qualifiers and except that in the case of a copy constructor or copy assignment operator, the parameter type may be “reference to non-const T”, where T is the name of the member function’s class) as if it had been implicitly declared,
在您的情况下,隐式声明的默认构造函数不会是函数模板,因此您不能显式默认它。
GCC 5.x 给出了您的代码的错误,error: a template cannot be defaulted
。
我尝试使用以下技术根据 class 模板参数的 属性 有条件地创建 默认构造函数 = default;
:
#include <type_traits>
#include <utility>
#include <iostream>
#include <cstdlib>
template< typename T >
struct identity
{
};
template< typename T >
struct has_property
: std::false_type
{
};
template< typename T >
struct S
{
template< typename X = T,
typename = std::enable_if_t< !has_property< X >::value > >
S(identity< X > = {})
{ std::cout << __PRETTY_FUNCTION__ << std::endl; }
template< typename X = T,
typename = std::enable_if_t< has_property< X >::value > >
#if 0
S() = default;
#else
S()
{ std::cout << __PRETTY_FUNCTION__ << std::endl; }
#endif
};
struct A {};
struct B {};
template<>
struct has_property< B >
: std::true_type
{
};
int main()
{
S< A >{};
S< B >{};
return EXIT_SUCCESS;
}
但是对于#if 1
它给出了一个错误:
main.cpp:32:11: error: only special member functions may be defaulted
S() = default;
^
template< ... > S()
不是 S
的 默认构造函数 的声明吗?
我将来可以使用即将到来的概念实现这样的调度吗?
我认为[dcl.fct.def.default]涵盖了这一点:
A function that is explicitly defaulted shall:
- be a special member function,
- have the same declared function type (except for possibly differing ref-qualifiers and except that in the case of a copy constructor or copy assignment operator, the parameter type may be “reference to non-const T”, where T is the name of the member function’s class) as if it had been implicitly declared,
在您的情况下,隐式声明的默认构造函数不会是函数模板,因此您不能显式默认它。
GCC 5.x 给出了您的代码的错误,error: a template cannot be defaulted
。