我想将模板化函数的特化的实现放到一个单独的源文件中,但是如果我尝试调用它(在 MyAction 中),我会收到此错误:
Explicit specialization has already been instantiated
Run Code Online (Sandbox Code Playgroud)
我不知道为什么会出现此错误。示例代码:
主程序
#include <iostream>
#include <string>
#include "MyClass.h"
int main()
{
std::cout << "Hello, " << XX::MyClass().MyMethod<1>() << std::endl;
std::cin.get();
}
Run Code Online (Sandbox Code Playgroud)
我的类.h
#pragma once
#include <string>
namespace XX {
struct MyClass {
std::string MyAction() {
return MyMethod<0>() + MyMethod<1>();
}
template<int>
std::string MyMethod();
};
template<>
std::string MyClass::MyMethod<0>();
template<>
std::string MyClass::MyMethod<1>();
}
Run Code Online (Sandbox Code Playgroud)
我的类.cpp
#include "MyClass.h"
namespace XX {
template<>
std::string MyClass::MyMethod<0>() {
return "FOO";
}
template<>
std::string MyClass::MyMethod<1>() {
return "BAR";
}
}
Run Code Online (Sandbox Code Playgroud)
是否有我不知道的模板实例化规则?
Mar*_*k R 10
好吧,看起来问题是订单。
当您定义MyAction编译器时,它会尝试实例化模板,但他不知道专业化。
当您在模板专业化后在 cpp 中声明MyAction和定义它时,它将起作用。
// header part
#include <string>
namespace XX {
struct MyClass {
template<int>
std::string MyMethod();
std::string MyAction();
};
}
// cpp part
namespace XX {
template<>
std::string MyClass::MyMethod<0>() {
return "a";
}
template<>
std::string MyClass::MyMethod<1>() {
return "b";
}
std::string MyClass::MyAction() {
return MyMethod<0>() + MyMethod<1>();
}
}
Run Code Online (Sandbox Code Playgroud)
请参阅此处: https: //godbolt.org/z/aGSB21
请注意,如果您移动MyClass::MyAction()上述MyClass::MyMethod<1>()错误,则会再次出现。
这是可以在头文件中声明专业化的版本:https ://godbolt.org/z/kHjlne
| 归档时间: |
|
| 查看次数: |
1245 次 |
| 最近记录: |