【发布时间】:2019-07-26 12:57:26
【问题描述】:
我想将模板化函数的特化实现放到一个单独的源文件中,但是如果我尝试调用它(在 MyAction 中),我会收到以下错误:
Explicit specialization has already been instantiated
我不知道为什么会出现此错误。 示例代码:
main.cpp
#include <iostream>
#include <string>
#include "MyClass.h"
int main()
{
std::cout << "Hello, " << XX::MyClass().MyMethod<1>() << std::endl;
std::cin.get();
}
MyClass.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>();
}
MyClass.cpp
#include "MyClass.h"
namespace XX {
template<>
std::string MyClass::MyMethod<0>() {
return "FOO";
}
template<>
std::string MyClass::MyMethod<1>() {
return "BAR";
}
}
是否有我不知道的模板实例化规则?
【问题讨论】:
-
VisualStudio 2017
-
我认为您不能将模板函数放在 cpp 文件中并从另一个翻译单元调用它们。据我所知,模板函数需要在头文件中或直接在调用它们的 cpp 文件中。
-
@rashmatash 不一定。如果您列出将使用的每个实例,则没有什么可以阻止您将模板放入 CPP。然而,这并不总是可行的。
-
是的,他可以。必须至少有一个翻译单元定义了模板的特定工具,其他翻译单元可以在不看定义的情况下使用它。
标签: c++