c++ - 类模板友好函数模板

标签 c++ templates

当我尝试从以下代码创建可执行文件时出现链接器错误。我得到的印象是我需要在周围放置一些“typename”或做一些前向声明;我尝试了几种组合,但都没有用。

template<typename T>
class enabled
{
  private:
    T type_;
    friend const T& typeof(const enabled<T>& obj); // Offending line
};

template<typename T>
const T& typeof(const enabled<T>& obj) {
    return obj.type_;
}


int main()
{
    enabled<std::string> en;
    std::cout << typeof(en);

    std::cin.clear(), std::cin.get();
    return 0;
}

1>main.obj : error LNK2001: unresolved external symbol "class std::string const& __cdecl typeof(class enabled<class std::string> const&)"

最佳答案

通过前向声明和指定函数是模板化的

template<typename T> class enabled;

template<typename T>
const T& typeof(const enabled<T>& obj) {
    return obj.type_;
}

template<typename T>
class enabled
{
  private:
    T type_;
    friend const T& typeof<>(const enabled<T>& obj);
};

关于c++ - 类模板友好函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7940703/

相关文章:

C++ : WordCount from Char string with pointers. ...?

c++ - 临时对象的 Clang 6 中的模板参数推导被破坏

c# - 在 c# 中的 grideview + 模板上设置交替行样式

c++ - 是否应该将运算符声明为非成员非模板 friend

c++ - 在 C++ 中,模板在我专门化时是否实例化了?

c++ - 在 C++11 中移出 std priority_queue 的元素

c++ - 链接静态库时避免链接未使用的符号

c++ - 用于 cout 顺序的 OpenMP 并行

c++ - 带有从 std::map 的迭代器到 std::list 的迭代器的 std::map

c++ - 模板参数、#define 和代码重复