给定以下类模板:
#include <type_traits>
template< class T, class Unrelated >
struct MyClass
{
static_assert( std::is_same< T, char >::value ||
std::is_same< T, char16_t>::value ||
std::is_same< T, char32_t >::value,
"MyClass only defined for char, char16_t, char32_t" );
MyClass( T init ) {}
MyClass( char32_t init ) {}
// ...
};
第二个 ( char32_t
) 构造函数是 T == char
的特例。和T == char16_t
.
显然,它会生成 T == char32_t
的错误。 。因此,我想针对这种情况“淘汰”该构造函数。该类相当大,大部分代码是为所有人共享的 T
,所以我不想让整个类(class)专门针对char32_t
案例。
我见过 enable_if
以及相关答案,如 this one在这里,但无法将任何提供的解决方案/示例适应我的具体情况(类模板中的非模板化构造函数)。
所以我请求您的帮助:
如何禁用MyClass( char32_t )
MyClass< T, U >
的构造函数与 T == char32_t
?
或者,如果更容易的话,如何禁用 MyClass( T init )
T == char32_t
的构造函数? (对于 char32_t
,两个构造函数在功能上是相同的。)
最佳答案
I have seen enable_if as well as related answers like this one here on SO, but was unable to adapt any of the presented solutions / examples to my specific case (non-templated constructor in class template).
您必须使用默认参数使构造函数模板化。然后确保 enable_if
取决于默认参数。不久:
//void_t trick made a type dependant
template<class T, class ... >
struct always
{
typedef T type;
};
template<class T, class ... D>
using always_t = typename always<T, D...>::type;
template<class T, class Unreleated>
class MyClass
{
public:
// ...
MyClass( T init )
{
}
template<class U = void>
MyClass( std::enable_if_t<
!std::is_same<T, char32_t>::value,
always_t<char32_t, U> //< enable_if expression depends on U
> init)
{
//decltype(init) is always char32_t, but the compiler can not know that
}
};
尝试一下 live .
关于c++ - 根据类模板参数淘汰类模板构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35102498/