【发布时间】:2016-04-04 19:46:49
【问题描述】:
是否可以测试某些类型是否可以通过 SFINAE 绑定到模板模板参数?
我认为最好用以下示例代码来解释我尝试做的事情:
#include <iostream>
template<typename... T> using void_t = void;
template<typename T> struct TemporaryBindObject
{
using type = TemporaryBindObject<T>;
};
template<template<typename...> class Dest> struct TestValidBind
{
template<typename... Ts> struct toTypesOf
{
using type = std::false_type;
};
template<template<typename...> class Src, typename... Ts> struct toTypesOf<Src<Ts...>, void_t<Dest<Ts...,float>>>
{
using type = std::true_type;
};
};
template<typename T> struct OneParamStruct{};
template<typename T1, typename T2> struct TwoParamStruct{};
int main()
{
using tmp = TemporaryBindObject<int>;
std::cout << "Can bind to TwoParamStruct: " << TestValidBind<TwoParamStruct>::toTypesOf<tmp>::type::value << std::endl;
std::cout << "Can bind to OneParamStruct: " << TestValidBind<OneParamStruct>::toTypesOf<tmp>::type::value << std::endl;
}
首先我创建一个临时类型tmp,我想从中获取模板参数int 将其绑定到另一个类模板。
对于TestValidBind<template template type>::toTypesOf<typename>,我想测试是否可以将给定类型的参数绑定到template template parameter 和 并附加一个附加类型(示例中为float)。
我想要的是TestValidBind<TwoParamStruct>::toTypesOf<tmp>::type 是true_type 而TestValidBind<OneParamStruct>::toTypesOf<tmp>::type 是false_type。
代码示例无法使用g++ -std=c++11 (5.3.1) 进行编译,并出现以下错误:
../test_SFINAE_with_template_binding.cc:在函数“int main()”中: ../test_SFINAE_with_template_binding.cc:34:96:错误: 'TestValidBind
::toTypesOf >::type' 没有被声明
如果删除了OneParamStruct 行,则报告false_type(这是错误的)。
使用clang++ -std=c++11 (3.8.0) 代码编译但在两种情况下都报告false_type。
这样的事情可能吗?
编辑:将附加类型从void 更改为float,以突出显示我想检查附加类型是否可行。
【问题讨论】:
标签: c++ templates c++11 metaprogramming