- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个模板类,它在其构造函数中使用了一个名称。该名称应该是实际类型的名称,以便可以将其放入人类可读的列表或其他内容中。
无论如何,我目前正在定义这样的类型:
typedef templateClass<someType> someTypeClass;
但是,为了让名称也成为“someTypeClass”,我需要用户始终正确指定该名称。相反,我想要一些方法来强制构造函数参数始终为“someTypeClass”(对于特定类型的特殊化)。
name 参数的目的是提供一种了解模板特化名称的方法。举个例子
template<class t>
class TemplateClass{
private:
std::string name;
t data;
public:
TemplateClass(const char* name);
/*Irrelevant*/
};
typedef TemplateClass<int> intType; //name should be "intType" but how can I force the name to be "intType" for this case? I dont want the user to have to type "intType" for every instance he wants to make
typedef TemplateClass<char> charType; //name should be "charType"
这是否可以通过某种可行的方式实现,或者是否有更好的方式来解决这个问题?
最佳答案
您可以将名称设为静态,并自行初始化。
template<class t>
class TemplateClass{
private:
static const std::string name;
t data;
public:
TemplateClass();
/*Irrelevant*/
}
typedef TemplateClass<int> intType;
template <>
const std::string TemplateClass<int>::name = "intType";
typedef TemplateClass<char> charType;
template <>
const std::string TemplateClass<char>::name = "charType";
请注意,使用这种方法,您可能希望将 std::string TemplateClass<int>::name;
在你的标题和你的 .cpp 中的初始化
用例子阐明我的笔记
模板类.hpp
#include <string>
template<class t>
class TemplateClass{
private:
static const std::string name;
t data;
public:
TemplateClass();
/*Irrelevant*/
}
typedef TemplateClass<int> intType;
template <>
const std::string TemplateClass<int>::name;
typedef TemplateClass<char> charType;
template <>
const std::string TemplateClass<char>::name;
模板类.cpp
#include "TemplateClass.hpp"
template <>
const std::string TemplateClass<int>::name = "intType";
template <>
const std::string TemplateClass<char>::name = "charType";
这里我们在 .hpp 中声明了特化变量,但只在 .cpp 中初始化它。否则,它将在您包含它的每个编译单元中进行初始化,并会出现多个定义错误。
补充说明
如果您使用的是 C++17,则可以使用新的 inline variable
做
template <>
inline const std::string TemplateClass<int>::name = "intType";
无需在 .cpp 文件中添加任何内容。
关于C++ 在为 "new"类型专门化模板时如何预定义构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48279528/
我有一个带有模板函数的基类,该函数具有通用模板类型和专用版本。 #ifndef BASE_CLASS #define BASE_CLASS #include using namespace std;
我有这个 3D vector 模板 template class Vec3TYPE{ public: union{ struct{ TYPE x,y,z; }; struct{ TY
我是一名优秀的程序员,十分优秀!