c++ - 测试模板化基础
问题描述
我试图为从特定模板化基础派生的类型创建一个简单的测试。这是代码。
#include <string>
template <class... T>
struct bar { };
struct foo : bar<>
{
template <class... T>
foo(T&&...) { }
};
template <class T>
struct is_bar {
private:
template <class... U>
static std::true_type test(bar<U...>);
static std::false_type test(...);
public:
static constexpr bool value = decltype(test(std::declval<T>()))::value;
};
template <class T>
void test(T&&) {
static_assert(is_bar<std::decay_t<T>>::value);
}
int main()
{
// Test 1: works
test(foo(std::string()));
// Test 2: works
std::string s;
foo f2(s);
test(f2);
// Test 3: not working
foo f3(std::string());
test(f3);
}
测试 1 和 2 工作正常。看评论。有人能指出为什么测试 3 会导致错误断言吗?
解决方案
欢迎来到最令人头疼的解析:f3
是一个函数。这是启用警告的编译器所说的:
prog.cpp:38:11: warning: parentheses were disambiguated as a function declaration [-Wvexing-parse]
foo f3(std::string());
^~~~~~~~~~~~~~~
prog.cpp:38:12: note: add a pair of parentheses to declare a variable
foo f3(std::string());
^
( )
因此std::declval<T>()
,在您的测试中是一个函数指针,显然不能转换为bar<U>
推荐阅读
- css - 如何修复滚动时通过标题显示的文本?
- node.js - 我可以制作一个仅适用于本地 Firebase 模拟器的云功能吗?
- uitableview - Xamarin.iOS 自定义单元格不显示来自 Interface Builder 的标签
- jquery - 使用 JQuery 将 span 元素更改为 textarea 元素
- html - Bootstrap 不充当 3 网格布局
- java - Janus Graph example-remotegraph 错误:未知的外部索引后端:jgex
- highcharts - 如何修复 highchart 以使用特殊标记正确显示系列
- postgresql - 如何使用 Hasura 和 Nextauth 在 DO 容器上公开 postgres 实例?
- javascript - 从 React + Apollo GraphQL 浏览器扩展中的扩展存储中获取令牌
- postgresql - Postgres 索引使用模式