gpt4 book ai didi

C++ 在为 "new"类型专门化模板时如何预定义构造函数参数

转载 作者:行者123 更新时间:2023-11-30 05:05:33 25 4
gpt4 key购买 nike

我有一个模板类,它在其构造函数中使用了一个名称。该名称应该是实际类型的名称,以便可以将其放入人类可读的列表或其他内容中。

无论如何,我目前正在定义这样的类型:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com