我尝试使用以下技术,根据类模板参数的属性有条件地使默认构造函数 = 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
的默认构造函数声明吗?
我能否在未来使用即将到来的概念来实现这样的分派?
constexpr
吗? - M.M