C++ 为交叉验证结果调用模板和专门化?
我正在尝试构建测试代码。我想调用模板代码和专门化代码来交叉验证结果 例如:C++ 为交叉验证结果调用模板和专门化?,c++,templates,template-specialization,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
// 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,“基本”实现
模板int Func()
{
//C/C++代码
返回x;
}
//功能2,不同的实现
模板int Func()
{
//ASM代码
#ifdef__GNUC__
...
#恩迪夫
返回x;
}
如何调用函数1和函数2来比较它们的结果?Func()
调用第一个函数,而Func()
调用第二个函数。模板参数推断失败,因为编译器无法自动计算出T
应该是什么,所以必须手动执行
我建议你使用数字而不是类型
template<int implementation = 0> //leave out default value if you have no default
int Func();
template <>
int Func<0>(){ return 42; } //default implementation
template <>
int Func<1>(){ return 42; } //alternative implementation 1
template <>
int Func<2>(){ return 42; } //alternative implementation 2
assert(Func() == Func<1>());
assert(Func() == Func<2>());
template//如果没有默认值,请省略默认值
int Func();
模板
int Func(){return 42;}//默认实现
模板
int Func(){return 42;}//可选实现1
模板
int Func(){return 42;}//可选实现2
断言(Func()==Func());
断言(Func()==Func());
您也可以使用
enum类而不是整数来给出实现名称,但是您可以只使用常规函数名而不是模板。我认为这是不可行的。假设您通过让编译器调用通用版本(例如在未显示专门化的单独转换单元中)来愚弄编译器,那么链接器应该抱怨函数的重复定义
还是内联起到了解救的作用?将函数体重构成具有独特名称的函数,使原始模板和专门化只是围绕它们的薄薄包装。这将允许您在内部单独测试实现(例如在单元测试中),同时保持用户代码的界面干净美观。通常,实现细节进入详细信息
名称空间。例如:
#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";
}
#包括
命名空间详细信息{
模板int FuncDefaultImpl(){
返回0;
}
int funcasimplforints(){
返回42;
}
}
模板int Func(){
返回详细信息::FuncDefaultImpl();
}
模板int Func(){
返回详细信息::funcasImplForInts();
}
void compareFuncImpls(){
std::cout如果您想为T=int
调用第一个函数,那么这是不可能的,因为当T
为int
时,编译器将选择第二个函数(并且您无法控制编译器的决定;那太晚了)。这就是模板的专门化的意思。@NawazFunc()
调用第一个函数,因此您可以手动选择所需的函数。T
在我看来在实现中没有实际使用。