【发布时间】:2017-11-22 16:15:40
【问题描述】:
我正在尝试为模板类 (CRTP) 专门化一些特征(例如 cppunit 中的 std::is_arithmetic 或 assertion_traits),它可以保存模板参数类型的值(类似于BOOST_STRONG_TYPEDEF)
我尝试使用 SFINAE 来限制我的专业化
示例代码适用于 gcc6 及更高版本,但无法使用 Visual c++(2015 或 2017)进行编译
error C2753: 'is_ar<T>': partial specialization cannot match argument list for primary template
或clang6
error: class template partial specialization does not specialize any template argument; to define the primary template, remove the template argument list
示例代码:
template<class T, typename B>
struct Base
{
using typed_type = T ;
using base_type = B ;
base_type x;
};
template <typename T>
struct MyType
{
using base_type = T;
base_type x;
};
struct CRTPInt : Base<CRTPInt, int> { };
template <typename T>
struct is_ar
{
static const bool value = false;
};
template <>
struct is_ar<int>
{
static const bool value = true;
};
template <class T, typename...>
using typer = T;
template <typename T>
struct is_ar<typer<T, typename T::base_type, typename T::typed_type>> : is_ar<typename T::base_type>
{
static const bool value = true;
};
static_assert(is_arithmetic<CRTPInt>::value, "failed");
static_assert(is_arithmetic<CRTPInt::base_type>::value, "failed");
我做错了什么?
它是有效的 c++11 吗? 如何使它与 Visual C++ 编译器一起工作?
假设我可以修改特征的初始定义,来自 max66 的答案可以正常工作。但在实践中,我想为宏创建的类专门化框架特征(例如 cppunit::assertion_traits)
#define MY_TYPEDEF(type , base) struct type: Base<type , base> { };
这个宏声明的类不是模板类,所以我没有找到一种方法来专门处理以这种方式生成的所有类。
唯一的共同点是类型名 base_type 和 typed_type 被定义。
有什么想法吗?
【问题讨论】:
标签: c++ c++11 template-specialization sfinae crtp