相关疑难解决方法(0)

为什么模板只能在头文件中实现?

引自C++标准库:教程和手册:

目前使用模板的唯一可移植方法是使用内联函数在头文件中实现它们.

为什么是这样?

(澄清:头文件不是唯一的便携式解决方案.但它们是最方便的便携式解决方案.)

c++ templates c++-faq

1660
推荐指数
14
解决办法
46万
查看次数

C++模板的朋友操作符重载

我的代码出了什么问题?

template<int E, int F>
class Float
{
 friend Float<E, F> operator+ (const Float<E, F> &lhs, const Float<E, F> &rhs);
};
Run Code Online (Sandbox Code Playgroud)

G ++只是警告:

float.h:7: warning: friend declaration ‘Float<E, F> operator+(const Float<E, F>&, const Float<E, F>&)’ declares a non-template function

float.h:7: warning: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here) -Wno-non-template-friend disables this warning

我试着add <> after the function name here在警告说明中提到,但是g ++给了我一个错误.

我用clang …

c++ templates operator-overloading friend

11
推荐指数
1
解决办法
2万
查看次数

声明模板朋友的语法背后的基本原理是什么?

声明模板函数的朋友涉及一些令人难以置信的不直观的语法,即使对于C++!选择额外<>需要的语法背后的理由是什么?使用template关键字不是更合理吗?

对于那些不了解这一点的人,这里有一个你可能尝试做的例子:

template <typename T>
class Foo
{
  int x;
  friend void bar(Foo<T>);
};

template <typename T>
void bar(Foo<T> f)
{
  std::cout << f.x;
}
Run Code Online (Sandbox Code Playgroud)

如果您尝试调用bar(Foo<T>()),则会出现链接器错误.

要解决这个问题,你必须转发声明bar(因此Foo),然后<>在朋友声明中粘贴一个奇怪的位置.

template <typename T> class Foo;
template <typename T> void bar(Foo<T>);

template <typename T>
class Foo
{
  int x;
  friend void bar<>(Foo<T>); // note the <> (!?)
};

template <typename T>
void bar(Foo<T> f)
{
    std::cout << f.x;
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,<>语法背后的基本原理是什么?使用 …

c++ syntax templates friend

9
推荐指数
2
解决办法
205
查看次数

标签 统计

c++ ×3

templates ×3

friend ×2

c++-faq ×1

operator-overloading ×1

syntax ×1