【问题标题】:C++: Using a Template for a Constructor [duplicate]C ++:为构造函数使用模板[重复]
【发布时间】: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 文件中?

标签: c++ class templates


【解决方案1】:

我怀疑您已经在 .cpp 文件中定义了您的 ctor。您必须在标题中定义您的template。

// class.hpp

class Class
{
public:
     template<typename T>
     Class( T arg )
     {
         // Define the ctor body here.
     }
};

【讨论】:

  • 在这种情况下显式限定符有什么作用?
  • 它阻止 ctor 隐式转换类型。这是一种很好的做法,但不是必需的。如果您愿意,可以将其删除。
  • 你能举个例子说明什么时候会出现问题吗?另外,一般什么时候使用显式?我从来没有真正使用过它。
  • 我将引导你到另一个线程来回答这个问题。有很好的例子解释了explicit 修复了什么问题。 stackoverflow.com/questions/121162/…
  • 在header 中定义constructor 正文是否解决了您的问题?
猜你喜欢
  • 1970-01-01
  • 2013-05-30
  • 1970-01-01
  • 2013-04-21
  • 2015-09-30
  • 1970-01-01
  • 2011-05-24
  • 2015-12-08
相关资源
最近更新 更多