【发布时间】:2020-04-19 00:12:46
【问题描述】:
是否可以在构造函数上使用模板,例如:
class Class {
public:
template<typename T>
Class(T arg);
};
还有cpp文件:
#include "class.h"
template<typename T>
Class::Class (T arg) {
// do something
}
构造函数被调用:
int a = 0;
Class c {a};
编译此代码时,我收到以下错误:
/usr/bin/ld: /tmp/ccNzp4z7.o: in function `main':
main.cpp:(.text+0x1c): undefined reference to `Class::Class<int>(int)'
collect2: error: ld returned 1 exit status
它的用途是构造函数,例如:
Class(std::unordered_set<T> choices, std::unordered_map<Direction, std::function<std::string(T)>> mapping);
choices 中的每个对象将针对映射中的每个Direction 进行迭代并传递给相应的函数,以生成对象。在这种情况下,构造函数执行完成后,使用的类型与类无关,所以我认为在整个类上使用模板没有意义。
【问题讨论】:
-
是的,构造函数可以是模板。
-
当您尝试编译并运行它时会发生什么?
-
如果
choices和mapping是成员变量,那么您需要模板化class而不仅仅是ctor。 -
我在问题中添加了错误,我可能应该包含它
-
您的
constructor是在哪里定义的?在.cpp文件中?