OP 中的唯一目的是foo
在实例化时触发检查。这就是你需要变量的原因hello
:它是foo
.
我宁愿遵循<type_traits>
. 更准确地说,我会perform_checks
变成class
(或struct
)有公共static constexpt bool
成员被称为value
是true
或false
取决于给定类型是否通过测试。然后如果是假的,我会用一个static_assert
来停止编译。value
我的解决方案假设模板类型参数的数量是偶数,如下:
#include <type_traits>
template<typename First, typename Second, typename... Others>
struct perform_checks :
std::integral_constant<bool,
perform_checks<First, Second>::value && // Checks First and Second
perform_checks<Others...>::value // Recursively "calls" itself on Others
> {
};
// This specialization finishes the recursion and effectively performs the test
template<typename First, typename Second>
struct perform_checks<First, Second> :
std::integral_constant<bool,
std::is_default_constructible<First>::value && // Checks First
std::is_copy_constructible<Second>::value // Checks Second
> {
};
这是一个简单的测试:
struct NonDefaultConstructible {
NonDefaultConstructible() = delete;
};
struct NonCopyConstructible {
NonCopyConstructible(const NonCopyConstructible&) = delete;
};
int main() {
static_assert(perform_checks<int, double>::value, "Failure");
static_assert(perform_checks<int, int, double, double>::value, "Failure");
static_assert(!perform_checks<NonDefaultConstructible, int>::value, "Failure");
static_assert(!perform_checks<int, NonCopyConstructible>::value, "Failure");
static_assert(!perform_checks<int, int, double, NonCopyConstructible>::value, "Failure");
}
请注意,没有创建任何变量。