c++ - 调用模板和特化来交叉验证结果?

标签 c++ templates template-specialization

我正在尝试构建测试代码。我想同时调用模板代码和特化代码来交叉验证结果。

例如:

// Function 1, "base" implementation
template <class T> int Func()
{
    // C/C++ code
    return x;
}

// Function 2, different implementation
template <> int Func<int>()
{
    // ASM code
    #ifdef __GNUC__
    ...
    #endif
    return x;
}

如何调用函数 1 和函数 2 来比较它们的结果?

最佳答案

将函数体重构为具有独特名称的函数,使原始模板和特化只是它们周围的薄包装。这将允许您在内部单独测试实现(例如在单元测试中),同时保持用户代码界面干净美观。通常实现细节进入 details 命名空间。示例:

#include <iostream>

namespace details {
template <class T> int FuncDefaultImpl() {
    return 0;
}

int FuncAsmImplForInts() {
    return 42;
}
}

template <class T> int Func() {
    return details::FuncDefaultImpl<T>();
}

template <> int Func<int>() {
    return details::FuncAsmImplForInts();
}

void compareFuncImpls() {
    std::cout << details::FuncDefaultImpl<int>() << "\n";
    std::cout << Func<int>()<< "\n";
}

int main() {

    // Internal testing
    std::cout << details::FuncDefaultImpl<int>() << "\n";
    std::cout << Func<int>() << "\n";

    // External interface
    std::cout << Func<float>() << "\n";
    std::cout << Func<int>() << "\n";
}

关于c++ - 调用模板和特化来交叉验证结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31468890/

相关文章:

c++ - 使用默认关键字时的 Visual Studio C2580

c++ - 为 void 类型部分特化参数包参数的语法是什么?

C++14 警告 : too many template headers for variable (should be 0)

c++ - 如何在不复制和粘贴整个类主体的情况下专门化模板?

c++ - 二维正态分布 C++

c++ - 代码不从文件C++读取文本

c++ - 模板包扩展以将函数应用于连续的参数对

c++ - 特征和将特征作为模板参数传递

c++ - 移动大数字

c++ - 在共享库中使用重载的new/delete和STL