【发布时间】:2014-02-21 15:23:18
【问题描述】:
我想检查是否可以使用给定的一组参数来专门化模板。以下是仅接受 1 个参数的模板版本:
#include <iostream>
template<template<typename...> class C, typename T>
struct is_valid_specialization {
typedef struct { char _; } yes;
typedef struct { yes _[2]; } no;
template<template<typename...> class D, typename U>
static yes test(D<U>*);
template<template<typename...> class D, typename U>
static no test(...);
constexpr static bool value = (sizeof(test<C, T>(0)) == sizeof(yes));
};
template<typename T>
struct Test1 { };
template<typename T1, typename T2>
struct Test2 { };
template<typename...>
struct TestV { };
int main() {
std::cout << "Test1<T>: " << is_valid_specialization<Test1, int>::value << std::endl;
std::cout << "Test2<T>: " << is_valid_specialization<Test2, int>::value << std::endl;
std::cout << "TestV<T>: " << is_valid_specialization<TestV, int>::value << std::endl;
}
这个does the job 用于模板只接受一个参数,但显然我也希望能够将它与多个参数一起使用,所以我尝试了这个:
template<template<typename...> class C, typename... T>
struct is_valid_specialization {
typedef struct { char _; } yes;
typedef struct { yes _[2]; } no;
template<template<typename...> class D, typename... U>
static yes test(D<U...>*);
template<template<typename...> class D, typename... U>
static no test(...);
constexpr static bool value = (sizeof(test<C, T...>(0)) == sizeof(yes));
};
现在事情变得奇怪了,因为现在是value is always false。
我有什么遗漏吗?这两个版本之间有什么完全不同的地方?还有其他方法可以实现吗?
【问题讨论】:
-
当我不知道这样的事情有什么问题时,我会注释掉备用函数 (
no test(...)) 并查看错误消息的内容。在这种情况下,编译器一直抱怨 D 的模板参数太多。打败我... -
顺便说一下,这些只测试参数是否匹配模板参数列表,而不是模板的完整实例化是否真的成功。后者是不可能的。
标签: c++ templates c++11 variadic-templates sfinae