首页 > 解决方案 > 测试模板化基础

问题描述

我试图为从特定模板化基础派生的类型创建一个简单的测试。这是代码。

#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 会导致错误断言吗?

标签: c++c++14

解决方案


欢迎来到最令人头疼的解析: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>


推荐阅读