C++ 根据类模板参数删除类模板构造函数
给定以下类模板:C++ 根据类模板参数删除类模板构造函数,c++,templates,c++11,C++,Templates,C++11,给定以下类模板: #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_sam
#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\u t构造函数是t==char和t==char16\u t的特例
显然,它会为T==char32\u T生成一个错误。所以,我想在这种情况下去掉构造器。这个类相当大,大部分代码都是为所有T共享的,因此我不希望为char32\u T案例专门化整个类
我已经看到了类似于这里的相关答案,但无法将任何呈现的解决方案/示例改编为我的特定案例类模板中的非模板构造函数
因此,我请求您的帮助:
如何为t==char32\U t的MyClass或者,如果这更简单,如何禁用T==char32\T的MyClass T init构造函数?对于char32\u t,这两个构造函数在功能上是相同的。这并不是您所要求的解决方案,但它可能会解决潜在的问题 您可以在Base中实现核心功能,然后定义:
template <typename T, typename U> struct MyClass : Base<T, U> {
using Base::Base;
};
template <typename U> struct MyClass<char32_t, U> : Base<char32_t, U> {
using Base::Base;
MyClass(char32_t init) { /* your constructor here */ }
};
我已经在这里看到了enable_if以及类似的相关答案
因此,但无法调整所提供的任何解决方案/示例
对于我的特定情况,类模板中的非模板构造函数
必须使用默认参数将构造函数模板化。然后确保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
}
};
试试看。这不是走错路了吗?为t==char32\u t启用char32\u t构造函数?如果使用非char32\u t实例化,这在技术上仍然是格式错误的NDR。无法为不允许专门化的构造函数模板生成有效的专门化enable\U if,因此enable\U if::type始终无效。@t.C.在我的代码中交换always\U t和Char32\U t可以解决问题吗?当然可以,或者类U=t,然后始终使用U而不是t。