c++ - 如何使用 C++11 type_traits 创建自定义元编程测试结构?

标签 c++ testing c++11 metaprogramming typetraits

如何在 C++11 中编写自定义元编程测试?我想写这样的东西:

#include <type_traits>
#include <iostream>

struct A {};

template <typename T>
struct foo {
    typedef typename std::conditional<std::is_pointer<T>::value,
                                      typename std::remove_pointer<T>::type,
                                      T>::type type;
};

template <typename A, typename B>
struct test1{typedef typename std::is_same<A, B>::value result;};

template <typename A, typename B>
struct test2{typedef typename std::is_same<A, typename foo<B>::type>::value result;};

template <typename A, typename B>
void testAll() {
    std::cout << std::boolalpha;
    std::cout << "test1: " << typename test1<A,B>::result << std::endl; // ERROR: expected ‘(’ before ‘<<’ token
    std::cout << "test2: " << typename test2<A,B>::result << std::endl; // ERROR: expected ‘(’ before ‘<<’ token
    // ...
}

int main()
{  
    typedef A type1;
    testAll<A, type1>();
    typedef const A* type2;
    testAll<A, type2>();
    // ...
}

我从 here 看到了一个可能的 is_same 实现.我需要这样的东西吗?

可以这么写:

std::cout << "test1: " << std::is_same<A, B>::value << std::endl;

我想这样写:

 std::cout << "test1: " << test1<A, B>::result << std::endl;

最佳答案

您正在使用 typename之前 test1<A,B>::result ,但这是不合适的,因为你想要 result成为一个,而不是一个类型。出于同样的原因,你不应该将它定义为 test1<> 中的类型别名。 : 您只是希望它具有由 std::is_same<>::value 返回的相同 (这是一个 static const bool 成员变量,而不是类型名称)。

你可以这样写:

template <typename A, typename B>
struct test1
{ 
    static const bool result = std::is_same<A, B>::value;
};

这样下面的行将被编译:

std::cout << "test1: " << test1<A,B>::result << std::endl;

但是,您的 test1<> trait 只不过是 std::is_same<> 的别名而已(使用 result 而不是 value ),并且 C++11 支持别名模板:

template <typename A, typename B>
using test1 = std::is_same<A, B>;

这将使您能够:

std::cout << "test1: " << test1<A,B>::value << std::endl;

test2<> trait 也有类似的问题,因为它定义了 result作为类型别名,但是 std::is_same<A, typename foo<B>::type>::value是一个值,而不是一个类型。

因此您可以再次将其重写如下:

template <typename A, typename B>
struct test2
{
    static const bool result = std::is_same<A, typename foo<B>::type>::value;
};

这样下面的行将被编译:

std::cout << "test2: " << test2<A, B>::result << std::endl;

但同样,您也可以定义一个别名模板:

template <typename A, typename B>
using test2 = std::is_same<A, typename foo<B>::type>;

关于c++ - 如何使用 C++11 type_traits 创建自定义元编程测试结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15393746/

相关文章:

c# - 如何在我的错误日志中使用步骤的名称? NUnit、Specflow、C#

c++ - Eigen Sparse value_Ptr 显示零,同时忽略有效值

c++ - 获取没有实例的 std::bitset 的大小

c++ - Visual Studio 2015 在 constexpr 中使用 lambda

reactjs - Mocha/Chai 测试 : How can I make it more strict?

C++ 分发具有依赖关系的程序

c++ - 使 Doxygen 读取双斜杠 C++ 注释作为标记

c++ - Xcode 推断命名空间?

c++ - 如何为 C++ 创建 Visual Studio 调试器可视化器

php - 测试失败,显示 "Booting the kernel before calling "...\WebTestCase::createClient()"不受支持